Java源码示例:com.github.tomakehurst.wiremock.junit.WireMockRule

示例1
private void initializeServiceQueryStubs(WireMockRule rule,
		List<Integer> persistencePorts, List<Integer> recommenderPorts)
		throws JsonProcessingException {
	List<String> persistences = new LinkedList<String>();
	for (int persistencePort: persistencePorts) {
		persistences.add("localhost:" + persistencePort);
	}
	String json = new ObjectMapper().writeValueAsString(persistences);
	rule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.PERSISTENCE.getServiceName() + "/"))
					.willReturn(WireMock.okJson(json)));
	List<String> recommenders = new LinkedList<String>();
	for (int recommenderPort: recommenderPorts) {
		recommenders.add("localhost:" + recommenderPort);
	}
	json = new ObjectMapper().writeValueAsString(recommenders);
	rule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.RECOMMENDER.getServiceName() + "/"))
					.willReturn(WireMock.okJson(json)));
}
 
示例2
@Before
public void setup() throws Exception {
    super.setup();
    this.authenticatedUser = login();
    WireMockRule bitbucketApi = getWireMockRule();

    String files = wireMockFileSystemPath()+"__files";
    String mappings = wireMockFileSystemPath()+"mappings";
    String proxyUrl = wireMockProxyUrl();

    new File(mappings).mkdirs();
    new File(files).mkdirs();
    bitbucketApi.enableRecordMappings(new SingleRootFileSource(mappings),
            new SingleRootFileSource(files));

    if (useProxy) {
        bitbucketApi.stubFor(
            WireMock.get(urlMatching(".*")).atPriority(10).willReturn(aResponse()
                .proxiedFrom(proxyUrl)));
    }

    this.apiUrl = String.format("http://localhost:%s",bitbucketApi.port());
}
 
示例3
private static WireMockRule createWireMockServerRule(String resourceFolder) {
    final WireMockRule rule = new WireMockRule(
        wireMockConfig()
            .dynamicPort()
            .usingFilesUnderClasspath(resourceFolder)
    );

    String mappingsPath = String.format("src/test/resources/%s/mappings", resourceFolder);
    String filesPath = String.format("src/test/resources/%s/__files", resourceFolder);

    new File(mappingsPath).mkdirs();
    new File(filesPath).mkdirs();

    rule.enableRecordMappings(
        new SingleRootFileSource(mappingsPath),
        new SingleRootFileSource(filesPath)
    );

    return rule;
}
 
示例4
public TestRealm(WireMockRule wireMockRule, String userInfoServerUrl, String emailFieldName, String groupFieldName) throws IOException {
    super(
         CLIENT_ID,
        "secret",
        null,
        "http://localhost:" + wireMockRule.port() + "/token",
        "http://localhost:" + wireMockRule.port() + "/authorization",
         userInfoServerUrl,
        null,
        null,
        null,
         FULL_NAME_FIELD,
         emailFieldName,
        null,
         groupFieldName,
        false,
        false,
        null,
        null,
        false,
        null,
        null,
        null,
        "manual"
    );
}
 
示例5
/**
 * @deprecated use {@link #getWireMockServer()} method instead. Note that
 *             WireMockServer is the base class of WireMockRule.
 *
 */
@Nullable
@Deprecated
public WireMockRule getWireMockRule() {
	throw new UnsupportedOperationException(
			"Deprecated since version 2.6.0. Please use getWireMockServer instead. WireMockServer is the base class of WireMockRule.");
}
 
示例6
/**
 * Create a mock persistence using a wire mock rule.
 * Recommended: Use {@link #DEFAULT_MOCK_PERSISTENCE_PORT} as port.
 * @param rule The wire mock rule to create the mocking stubs for.
 */
public MockPersistenceProvider(WireMockRule rule) {
	this.port = rule.port();
	rule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/" + Service.PERSISTENCE.getServiceName() + "/rest/orders"))
					.willReturn(WireMock.okJson(getOrders())));
	rule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/" + Service.PERSISTENCE.getServiceName() + "/rest/orderitems"))
					.willReturn(WireMock.okJson(getOrderItems())));
	rule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/" + Service.PERSISTENCE.getServiceName() + "/rest/generatedb/finished"))
					.willReturn(WireMock.ok("true")));
}
 
示例7
private void initializeUpdateAndHeartbeatStubs(WireMockRule rule) {
	rule.stubFor(WireMock.put(WireMock.urlMatching(
			"/tools.descartes.teastore.registry/rest/services/.*"))
					.willReturn(WireMock.ok()));
	rule.stubFor(WireMock.delete(WireMock.urlMatching(
			"/tools.descartes.teastore.registry/rest/services/.*"))
					.willReturn(WireMock.ok()));
}
 
示例8
private void initializeMockRegistry(WireMockRule wireMockRule, int count, int startport)
		throws JsonProcessingException {
	List<String> strings = new LinkedList<String>();
	for (int i = 0; i < count; i++) {
		strings.add("localhost:" + (startport + i));
	}
	String json = new ObjectMapper().writeValueAsString(strings);
	wireMockRule.stubFor(WireMock.get(WireMock.urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.PERSISTENCE.getServiceName()))
					.willReturn(WireMock.okJson(json)));
	wireMockRule.stubFor(WireMock.post(WireMock.urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/"
					+ Service.PERSISTENCE.getServiceName() + "/*"))
	.willReturn(WireMock.ok()));
}
 
示例9
protected static WireMockRule createWireMockServerRule(String resourceFolder, String baseUrl) {
    ReplaceUrlTransformer replaceUrlTransformer = new ReplaceUrlTransformer();

    final WireMockRule rule = new WireMockRule(
        wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .usingFilesUnderClasspath(resourceFolder)
            .extensions(
                new GzipDecompressTransformer(),
                replaceUrlTransformer
            )
    );

    String mappingsPath = String.format("src/test/resources/%s/mappings", resourceFolder);
    String filesPath = String.format("src/test/resources/%s/__files", resourceFolder);

    new File(mappingsPath).mkdirs();
    new File(filesPath).mkdirs();

    rule.enableRecordMappings(
        new SingleRootFileSource(mappingsPath),
        new SingleRootFileSource(filesPath)
    );

    if (useProxy) {
        rule.stubFor(
            WireMock.get(urlMatching(".*"))
                .atPriority(10)
                .willReturn(aResponse().proxiedFrom(baseUrl)));
    }

    replaceUrlTransformer.configure(baseUrl, rule);

    return rule;
}
 
示例10
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例11
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .needClientAuth(true)
            .trustStorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/truststore01.jks"))
            .trustStorePassword("password")
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例12
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .needClientAuth(true)
            .trustStorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/truststore01.jks"))
            .trustStorePassword("password")
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例13
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例14
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .needClientAuth(true)
            .trustStorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/truststore01.jks"))
            .trustStorePassword("password")
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例15
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .needClientAuth(true)
            .trustStorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/truststore01.jks"))
            .trustStorePassword("password")
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例16
@Override
protected WireMockRule getWiremockRule() {
    return new WireMockRule(wireMockConfig()
            .dynamicPort()
            .dynamicHttpsPort()
            .keystorePath(ResourceUtils.toPath("io/gravitee/gateway/standalone/keystore01.jks"))
            .keystorePassword("password"));
}
 
示例17
public static void stubPublicAuthV1ApiAuth(WireMockRule wireMockRule, Account account, String token) throws JsonProcessingException {
    Map<String, String> entity = ImmutableMap.of("account_id", account.getAccountId(), "token_type", account.getPaymentType().name());
    String json = new ObjectMapper().writeValueAsString(entity);
    wireMockRule.stubFor(get(urlEqualTo("/v1/api/auth"))
            .withHeader(AUTHORIZATION, equalTo("Bearer " + token))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(json)));
}
 
示例18
public WireMockRule getRule(Options options) {
    if (urlToMock != null && !urlToMock.isEmpty()) {
        return new WireMockRecorderRule(options, urlToMock);
    } else {
        return new WireMockRule(options);
    }
}
 
示例19
@AfterEach
void tearDown() {
    List.of(mockApmServer1, mockApmServer2).forEach(WireMockRule::stop);
}
 
示例20
@BeforeClass
public static void CucumberRestStepsTestCase() {
  wm = new WireMockRule(8080);
  wm.start();

  stubFor(
      get("/")
          .willReturn(ok())
  );

  stubFor(
      post("/withData")
          .withRequestBody(equalToJson("{\"test\": \"test\"}"))
          .willReturn(okJson("{\"foo\": \"bar\"}"))
  );

  stubFor(
      post("/withData")
          .withRequestBody(equalToJson("[{\"test\": \"test\"}]"))
          .willReturn(okJson("{\"foo\": \"bar\"}"))
  );

  stubFor(
      get(urlPathEqualTo("/withParams"))
          .withQueryParam("param", equalTo("paramValue"))
          .willReturn(okJson("[]"))
  );

  stubFor(
      get("/withHeaders")
          .withHeader("MyHeader", equalTo("MyHeaderValue"))
          .willReturn(
              aResponse()
                  .withHeader("MyHeader", "MyHeaderValue")
                  .withHeader("MultiHeader", "MultiHeaderValue1", "MultiHeaderValue2")
          )
  );

  stubFor(
      get("/withArray")
          .willReturn(okJson("[{\"foo\": \"bar\"}, {\"foo\": 3}, {\"foos\": [\"bar\", \"wee\"]}]"))
  );

  stubFor(
      get("/response")
          .willReturn(okJson("{\"foo\": \"bar\"}"))
  );

  stubFor(
      get("/response/bar")
          .willReturn(okJson("{\"bar\": \"wee\"}"))
  );

  stubFor(
      post("/withFile")
          .withMultipartRequestBody(
              aMultipart()
                  .withName("file")
          )
          .willReturn(ok())
  );
}
 
示例21
protected void verifyWireMock(WireMockRule wiremock) {
    // override in derived class for extra verification
}
 
示例22
@Override
protected void verifyWireMock(WireMockRule wiremock) {
    wiremock.verify(postRequestedFor(urlEqualTo("/"))
        .withBasicAuth(new BasicCredentials(TEST_USER, TEST_PASSWORD)));
}
 
示例23
@Override
protected WireMockRule wireMock() {
    return wireMock;
}
 
示例24
@Override
protected WireMockRule wireMock() {
    return wireMock;
}
 
示例25
@Override
protected WireMockRule wireMock() {
    return wireMock;
}
 
示例26
@Override
protected WireMockRule wireMock() {
    return wireMock;
}
 
示例27
public static void verifyRequestCount(int expectedCount, WireMockRule wireMock) {
    wireMock.verify(expectedCount, anyRequestedFor(anyUrl()));
}
 
示例28
/**
 * Create a Tomcat test handler for persistence testing.
 * @param count Number of testing tomcats.
 * @param startPort Port to start with (do not use 0 for auto-assigning).
 * @param wireMockRule Wire mock rule for mocking the registry.The test handler will
 * add all services with respective stubs to the rule.
 * @param endpoints Class objects for the endpoints.
 * @throws ServletException Exception on failure.
 * @throws LifecycleException Exception on failure.
 * @throws JsonProcessingException Exception on failure.
 */
public TomcatTestHandler(int count, int startPort, WireMockRule wireMockRule, Class<?>... endpoints)
		throws ServletException, LifecycleException, JsonProcessingException {
	tomcats = new Tomcat[count];
	EMFManagerInitializer.initializeEMF();
	for (int i = 0; i < count; i++) {
		tomcats[i] = new Tomcat();
		tomcats[i].setPort(startPort + i);
		tomcats[i].setBaseDir(testWorkingDir);
		Context context = tomcats[i].addWebapp(CONTEXT, testWorkingDir);
		//Registry
		if (wireMockRule != null) {
			ContextEnvironment registryURL = new ContextEnvironment();
			registryURL.setDescription("");
			registryURL.setOverride(false);
			registryURL.setType("java.lang.String");
			registryURL.setName("registryURL");
			registryURL.setValue("http://localhost:" + wireMockRule.port()
			+ "/tools.descartes.teastore.registry/rest/services/");
			context.getNamingResources().addEnvironment(registryURL);
			ContextEnvironment servicePort = new ContextEnvironment();
			servicePort.setDescription("");
			servicePort.setOverride(false);
			servicePort.setType("java.lang.String");
		    servicePort.setName("servicePort");
		    servicePort.setValue("" + startPort + i);
			context.getNamingResources().addEnvironment(servicePort);
			context.addApplicationListener(RegistrationDaemon.class.getName());
		}
		//REST endpoints
		ResourceConfig restServletConfig = new ResourceConfig();
		for (Class<?> endpoint: endpoints) {
			restServletConfig.register(endpoint);
		}
		ServletContainer restServlet = new ServletContainer(restServletConfig);
		tomcats[i].addServlet(CONTEXT, "restServlet", restServlet);
		context.addServletMappingDecoded("/rest/*", "restServlet");
		tomcats[i].start();
	}
	if (wireMockRule != null) {
		initializeMockRegistry(wireMockRule, count, startPort);
	}
	System.out.println("Initializing Database with size " + CategoryRepository.REPOSITORY.getAllEntities().size());
}
 
示例29
@Override
protected WireMockRule getWireMockRule() {
    return bitbucketApi;
}
 
示例30
@Override
protected WireMockRule getWireMockRule() {
    return bitbucketApi;
}