Best Karate code snippet using ui.MockRunner
Source:MockAsWarServlet.java
...19import com.eviware.soapui.DefaultSoapUICore;20import com.eviware.soapui.SoapUI;21import com.eviware.soapui.impl.wsdl.WsdlProject;22import com.eviware.soapui.impl.wsdl.mock.DispatchException;23import com.eviware.soapui.impl.wsdl.mock.WsdlMockRunner;24import com.eviware.soapui.impl.wsdl.mock.WsdlMockService;25import com.eviware.soapui.model.mock.MockResult;26import com.eviware.soapui.model.mock.MockRunner;27import com.eviware.soapui.model.mock.MockService;28import com.eviware.soapui.model.project.ProjectFactoryRegistry;29import com.eviware.soapui.monitor.MockEngine;30import com.eviware.soapui.support.SoapUIException;31import com.eviware.soapui.support.StringUtils;32import com.eviware.soapui.support.Tools;33import com.eviware.soapui.support.editor.inspectors.attachments.ContentTypeHandler;34import com.eviware.soapui.support.types.StringToStringsMap;35import com.eviware.soapui.support.xml.XmlUtils;36import org.apache.commons.collections.list.TreeList;37import org.apache.log4j.spi.LoggingEvent;38import org.apache.xmlbeans.XmlException;3940import javax.servlet.ServletContext;41import javax.servlet.ServletException;42import javax.servlet.http.HttpServlet;43import javax.servlet.http.HttpServletRequest;44import javax.servlet.http.HttpServletResponse;45import java.io.File;46import java.io.FileInputStream;47import java.io.IOException;48import java.io.PrintWriter;49import java.util.ArrayList;50import java.util.List;51import java.util.logging.Level;52import java.util.logging.Logger;5354/**55 * Servlet implementation class SoapUIMockServlet56 */57@SuppressWarnings("unchecked")58public class MockAsWarServlet extends HttpServlet {5960 private static final long serialVersionUID = 1L;61 protected static Logger logger = Logger.getLogger(MockAsWarServlet.class.getName());62 protected WsdlProject project;63 long maxResults;64 List<MockResult> results = new TreeList();65 private List<LoggingEvent> events = new TreeList();66 boolean enableWebUI;6768 public void init() throws ServletException {69 super.init();70 try {71 SoapUI.setSoapUICore(new MockServletSoapUICore(getServletContext()), true);7273 String mockServiceEndpoint = initMockServiceParameters();7475 logger.info("Loading project");7677 initProject(getServletContext().getRealPath(getInitParameter("projectFile")));7879 if (project == null || project.getName() == null) {80 initProject(getServletContext().getResource("/" + getInitParameter("projectFile")).toString());81 }8283 if (project == null) {84 logger.info("Starting Mock service(s)");85 }8687 for (MockService mockService : project.getMockServiceList()) {88 logger.info("Starting mock service [" + mockService.getName() + "]");89 if (StringUtils.hasContent(mockServiceEndpoint)) {90 ((WsdlMockService) mockService).setMockServiceEndpoint(mockServiceEndpoint);91 }9293 mockService.start();94 }9596 for (MockService mockService : project.getRestMockServiceList()) {97 logger.info("Starting REST mock service [" + mockService.getName() + "]");98 mockService.start();99 }100 } catch (Exception ex) {101 logger.log(Level.SEVERE, null, ex);102 }103 }104105 protected void initProject(String path) throws XmlException, IOException, SoapUIException {106 project = (WsdlProject) ProjectFactoryRegistry.getProjectFactory("wsdl").createNew(path);107 }108109 protected String initMockServiceParameters() {110 try {111 if (StringUtils.hasContent(getInitParameter("listeners"))) {112 logger.info("Init listeners");113 try {114 System.setProperty("soapui.ext.listeners", getServletContext().getRealPath(getInitParameter("listeners")));115 } catch (Exception e) {116 logger.info("Listeners not set! Reason : " + e.getMessage());117 }118 } else {119 logger.info("Listeners not set!");120 }121122 if (StringUtils.hasContent(getInitParameter("actions"))) {123 logger.info("Init actions");124 try {125 System.setProperty("soapui.ext.actions", getServletContext().getRealPath(getInitParameter("actions")));126 } catch (Exception e) {127 logger.info("Actions not set! Reason : " + e.getMessage());128 }129 } else {130 logger.info("Actions not set!");131 }132133 if (SoapUI.getSoapUICore() == null) {134 if (StringUtils.hasContent(getInitParameter("soapUISettings"))) {135 logger.info("Init settings");136 SoapUI.setSoapUICore(137 new MockServletSoapUICore(getServletContext(), getInitParameter("soapUISettings")), true);138 } else {139 logger.info("Settings not set!");140 SoapUI.setSoapUICore(new MockServletSoapUICore(getServletContext()), true);141 }142 } else {143 logger.info("SoapUI core already exists, reusing existing one");144 }145146 if (StringUtils.hasContent(getInitParameter("enableWebUI"))) {147 if ("true".equals(getInitParameter("enableWebUI"))) {148 logger.info("WebUI ENABLED");149 enableWebUI = true;150 } else {151 logger.info("WebUI DISABLED");152 enableWebUI = false;153 }154 }155156 }catch (Exception e){157 logger.info("Property set with error!"+e.getMessage());158 }159 try {160 maxResults = Integer.parseInt(getInitParameter("maxResults"));161 } catch (NumberFormatException ex) {162 maxResults = 1000;163 }164165 SoapUI.ensureGroovyLog().addAppender(new GroovyLogAppender());166167 return getInitParameter("mockServiceEndpoint");168 }169170 public void destroy() {171 super.destroy();172 getMockServletCore().stop();173 }174175 protected MockAsWarCoreInterface getMockServletCore() {176 return (MockAsWarCoreInterface) SoapUI.getSoapUICore();177 }178179 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,180 IOException {181 try {182 getMockServletCore().dispatchRequest(request, response);183 } catch (DispatchException ex) {184 logger.log(Level.SEVERE, null, ex);185 }186 }187188 private void printResult(PrintWriter out, MockResult result) {189190 out.print("<h4>Details for MockResult at " + new java.util.Date(result.getTimestamp()) + " ("191 + result.getTimeTaken() + "ms)</h4>");192193 out.println("<hr/><p><b>Request Headers</b>:</p>");194 out.print("<table border=\"1\"><tr><td>Header</td><td>Value</td></tr>");195 StringToStringsMap headers = result.getMockRequest().getRequestHeaders();196 for (String name : headers.getKeys()) {197 for (String value : headers.get(name)) {198 out.println("<tr><td>" + name + "</td><td>" + value + "</td></tr>");199 }200 }201 out.println("</table>");202203 out.println("<hr/><b>Incoming Request</b>:<br/><pre>"204 + XmlUtils.entitize(result.getMockRequest().getRequestContent()) + "</pre>");205206 out.println("<hr/><p><b>Response Headers</b>:</p>");207 out.print("<table border\"1\"><tr><td>Header</td><td>Value</td></tr>");208 headers = result.getResponseHeaders();209 for (String name : headers.getKeys()) {210 for (String value : headers.get(name)) {211 out.println("<tr><td>" + name + "</td><td>" + value + "</td></tr>");212 }213 }214 out.println("</table>");215216 out.println("<hr/><b>Returned Response</b>:<pre>" + XmlUtils.entitize(result.getResponseContent()) + "</pre>");217 }218219 class MockServletSoapUICore extends DefaultSoapUICore implements MockEngine, MockAsWarCoreInterface {220 private final ServletContext servletContext;221 private List<MockRunner> mockRunners = new ArrayList<MockRunner>();222223 public MockServletSoapUICore(ServletContext servletContext, String soapUISettings) {224 super(servletContext.getRealPath("/"), servletContext.getRealPath(soapUISettings));225 this.servletContext = servletContext;226 }227228 /*229 * (non-Javadoc)230 *231 * @see232 * com.eviware.soapui.mockaswar.MockAsWarCoreInterface#dispatchRequest233 * (javax.servlet.http.HttpServletRequest,234 * javax.servlet.http.HttpServletResponse)235 */236 @Override237 public void dispatchRequest(HttpServletRequest request, HttpServletResponse response) throws DispatchException,238 IOException {239 String pathInfo = request.getPathInfo();240 if (pathInfo == null) {241 pathInfo = "";242 }243244 MockRunner mockRunner = getMatchedMockRunner(getMockRunners(), pathInfo);245246 if (mockRunner != null) {247 MockResult result = mockRunner.dispatchRequest(request, response);248249 if (maxResults > 0) {250 synchronized (results) {251 while (maxResults > 0 && results.size() > maxResults) {252 results.remove(0);253 }254 if (result != null) {255 results.add(result);256 }257 }258 }259 return;260 }261262 if (enableWebUI) {263 String realPath = servletContext.getRealPath(pathInfo);264 File file = realPath == null ? null : new File(realPath);265 if (file != null && file.exists() && file.isFile()) {266 FileInputStream in = new FileInputStream(file);267 response.setStatus(HttpServletResponse.SC_OK);268 long length = file.length();269 response.setContentLength((int) length);270 response.setContentType(ContentTypeHandler.getContentTypeFromFilename(file.getName()));271 Tools.readAndWrite(in, length, response.getOutputStream());272 in.close();273 } else if (pathInfo.equals("/master")) {274 printMaster(request, response, mockRunners);275 } else if (pathInfo.equals("/detail")) {276 printDetail(request, response);277 } else if (pathInfo.equals("/log")) {278 printLog(request, response);279 } else {280 printFrameset(request, response);281 }282 } else {283 printDisabledLogFrameset(request, response);284 }285 }286287 private MockRunner getMatchedMockRunner(MockRunner[] mockRunners, String pathInfo) {288289 MockRunner mockRunner = null;290 String bestMatchedRootPath = "";291292 for (MockRunner runner : mockRunners) {293 String mockServicePath = runner.getMockContext().getMockService().getPath();294 if (pathInfo.startsWith(mockServicePath) && mockServicePath.length() > bestMatchedRootPath.length()) {295 bestMatchedRootPath = mockServicePath;296 mockRunner = runner;297 }298 }299300 return mockRunner;301302 }303304 /*305 * (non-Javadoc)306 *307 * @see com.eviware.soapui.mockaswar.MockAsWarCoreInterface#stop()308 */309 @Override310 public void stop() {311 for (MockRunner mockRunner : getMockRunners()) {312 mockRunner.stop();313 }314 }315316 public MockServletSoapUICore(ServletContext servletContext) {317 super(servletContext.getRealPath("/"), null);318 this.servletContext = servletContext;319 }320321 @Override322 protected MockEngine buildMockEngine() {323 return this;324 }325326 public MockRunner[] getMockRunners() {327 return mockRunners.toArray(new MockRunner[mockRunners.size()]);328 }329330 public boolean hasRunningMock(MockService mockService) {331 for (MockRunner runner : mockRunners) {332 if (runner.getMockContext().getMockService() == mockService) {333 return true;334 }335 }336337 return false;338 }339340 public void startMockService(MockRunner runner) throws Exception {341 mockRunners.add(runner);342 }343344 public void stopMockService(MockRunner runner) {345 mockRunners.remove(runner);346 }347 }348349 public void printMaster(HttpServletRequest request, HttpServletResponse response, List<MockRunner> mockRunners)350 throws IOException {351 response.setStatus(HttpServletResponse.SC_OK);352 response.setContentType("text/html");353354 PrintWriter out = response.getWriter();355 startHtmlPage(out, "MockService Log Table", "15");356357 out.print("<img src=\"header_logo.png\"><h3>SoapUI MockServices Log for project [" + project.getName()358 + "]</h3>" + "<p style=\"text-align: left\">WSDLs:");359360 for (MockRunner mockRunner : mockRunners) {361 String overviewUrl = ((WsdlMockRunner) mockRunner).getOverviewUrl();362 if (overviewUrl.startsWith("/")) {363 overviewUrl = overviewUrl.substring(1);364 }365366 out.print(" [<a target=\"new\" href=\"" + overviewUrl + "\">" + mockRunner.getMockContext().getMockService().getName()367 + "</a>]");368 }369370 out.print("</p>");371372 out.print("<hr/><p><b>Processed Requests</b>: ");373 out.print("[<a href=\"master\">Refresh</a>] ");374 out.print("[<a href=\"master?clear\">Clear</a>]</p>");375
...
MockRunner
Using AI Code Generation
1import 'package:mockito/mockito.dart';2import 'package:test/test.dart';3import 'package:ui/ui.dart';4class MockRunner extends Mock implements Runner {}5void main() {6 test('should return a valid result', () {7 final runner = MockRunner();8 when(runner.run()).thenReturn('Test');9 expect(runner.run(), 'Test');10 });11}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!