java 如何针对不同的测试方法使用不同的Map文件?

f1tvaqid  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(79)

我在我的@SpringBootTest中使用Wiremock(spring-cloud-contract-wiremock),所以:

import static com.github.tomakehurst.wiremock.client.WireMock.*;

@SpringBootTest
@AutoConfigureWireMock(port = 0)
class SomeTest {

    @Test
    void test1() {
        Wiremock.stubFor(get(urlPathEqualTo("/endpoint"))
                .willReturn(aResponse().withStatus(200))
        );

        //  start test
        //  assertThat response is 200
    }

    @Test
    void test2() {
        stubFor(get(urlPathEqualTo("/endpoint"))
                .willReturn(aResponse().withStatus(401))
        );

        // start test
        // assertThat response is 401
    }
}

因此,对于两个测试方法,我为同一个请求创建了不同的存根,并且效果很好。
另外,当使用Wiremock时,您可以在src/test/resources/mappings包中以JSON格式存储存根,但到目前为止,我只能实现这样的结果,即我只能有一个JSON文件来存储存根。
我如何为两个测试方法使用两个单独的JSON,以及如何告诉我的测试方法使用特定的JSON文件来加载Wiremock-stubs?
我正在使用spring-boot-parent 3.1.0和WireMock的这个maven依赖项:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-wiremock</artifactId>
    <version>4.0.2</version>
    <scope>test</scope>
</dependency>
flvlnr44

flvlnr441#

你可以做

@SpringBootTest
class SomeTest {
   private WireMockServer wireMockServer;

   @Before
   public void before() {
      wireMockServer = new WireMockServer(<port>);
   }

   @After
   public void after() {
      wireMockServer.resetAll();
      wireMockServer.stop();
   }

   @Test
   public void test1() {
      wireMockServer.addStubMapping(buildStubMapping("SomeTest/test1.json"));
      // test 1 specific assertions
   }

   @Test 
   public void test2() {
      wireMockServer.addStubMapping(buildStubMapping("SomeTest/test2.json"));
      // test 2 specific assertions
   }

   private StubMapping buildStubMapping(String path) {
      Resource resource = new ClassPathResource(path);
      String json = IOUtils.toString(resource.getInputStream());
      return StubMapping.buildFrom(json);
   }
}
fhg3lkii

fhg3lkii2#

1.使用spring-cloud-contract-wiremock的解决方案:

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;

@SpringBootTest
@AutoConfigureWireMock(port = 0)
class SomeTest {

    @Autowired
    private WireMockServer wireMockServer;

    @BeforeEach
    void setUp() {
        wireMockServer.resetAll();
    }

    @Test
    void test1() {
        String json = <json with mappings for 200 and others>;

        Json.read(json, new TypeReference<List<StubMapping>>(){})
                .forEach(wireMockServer::addStubMapping);

        //  start test
        //  assertThat response is 200
    }

    @Test
    void test2() {
        String json = <json with mappings for 401 and others>;

        Json.read(json, new TypeReference<List<StubMapping>>(){})
                .forEach(wireMockServer::addStubMapping);

        // start test
        // assertThat response is 401
    }
}

1.手动创建WireMockServer的解决方案:

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

import java.util.List;

import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

public class WiremockTest {

    private static final WireMockServer WIRE_MOCK_SERVER = new WireMockServer(wireMockConfig().dynamicPort());

    @DynamicPropertySource
    static void dynamicPropertySource(DynamicPropertyRegistry dynamicPropertyRegistry) {
        dynamicPropertyRegistry.add("wiremock.server.base-url", WIRE_MOCK_SERVER::baseUrl);

     //  with it we can change url in our application.yml
     //  like so: {wiremock.server.base-url}/endpoint
    }

    @BeforeAll
    static void startWireMock() {
        WIRE_MOCK_SERVER.start();
    }

    @AfterAll
    static void stopWireMock() {
        WIRE_MOCK_SERVER.stop();

    }

    @BeforeEach
    void clearWireMock() {
        WIRE_MOCK_SERVER.resetAll();
    }

    @Test
    void test1() {
        String json = <json with mappings for 200 and others>;
        
        Json.read(json, new TypeReference<List<StubMapping>>(){})
                .forEach(WIRE_MOCK_SERVER::addStubMapping);

        //  start test
        //  assertThat response is 200
    }

    @Test
    void test2() {
        String json = <json with mappings for 401 and others>;

        Json.read(json, new TypeReference<List<StubMapping>>(){})
                .forEach(WIRE_MOCK_SERVER::addStubMapping);
        
        // start test
        // assertThat response is 401
    }
}

json的格式必须如下:

[
  {
    "request": {
      "urlPath": "/endpoint",
      "method": "GET"
    },
    "response": {
      "status": 200,
      "jsonBody": {
        "foo": "bar"
      },
      "headers": {
        "Content-Type": "application/json"
      }
    }
  },
  {
    "request": {
      "urlPath": "/endpoint",
      "method": "PATCH"
    },
    "response": {
      "status": 202,
      "headers": {
        "Content-Type": "application/json"
      }
    }
  }
]
lvmkulzt

lvmkulzt3#

您可以使用ResponseDefinitionBuilder.withBodyFile(fileName),默认情况下,它将从src/test/resources获取源文件

@Test
void test1() {
   Wiremock.stubFor(
      get(urlPathEqualTo("/endpoint")).willReturn(
         aResponse()
            .withStatus(200)
            .withBodyFile("SomeTest/test1.json")
   );
   ...
}

相关问题