提问者:小点点

我们可以用类似于Wiremock的方式插入Spring Boot Test、Mockito或powerMock吗


就集成测试而言,Wiremock确实非常强大。我喜欢Wiremock在不改变beans的情况下处理< code>URL响应的方式(我们在mockito或powermock中进行单元测试的方式)。

    @Mock
    SomeRepository someRepository; //Zombie mutation

    @Mock
    AnotherComponent anotherComponent; //mutation

    @InjectMocks
    SomeService someService; //mutation - This is the class we are unit testing

在集成测试中,我希望所有3个层都得到测试并模拟外部依赖

                      +---> Repository -----> MySQL (I managed this with in-memory h2 database)
                      |
controller---> service 
                      | 
                      +---> Proxy ---------> Another REST service (some way to mock the call???)

是否可以对 Spring 启动测试、mockito 或 powermock 做同样的事情(因为我已经在使用它们,只是不想向项目添加新库)

以下是我们如何在Wiresck中进行存根。

 service.stubFor(get(urlEqualTo("/another/service/call"))
                .willReturn(jsonResponse(toJson(objResponse))));

上面的代码意味着,在我们的测试中,每当调用外部服务(http://example.com/another/service/call)时,它都会被拦截并注入示例响应——并且外部调用不会离开系统

示例代码

@SpringBootTest
@AutoConfigureMockMvc
public class StubTest {
    @Autowired
    private MockMvc mockMvc;

    private MockRestServiceServer server;

    @BeforeEach
    public void init() {
        RestTemplate restTemplate = new RestTemplate();
        server = MockRestServiceServer.bindTo(restTemplate).build();
    }

    @Test
    public void testFakeLogin() throws Exception {
        String sampleResponse = stubSampleResponse();

        //Actual URL to test
        String result = mockMvc.perform(get("/s1/method1")
                .contentType("application/json"))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

        assertThat(result).isNotNull();
        assertThat(result).isEqualTo(sampleResponse);
    }

    private String stubSampleResponse() {

        String response = "Here is response";

        //URL to stub (this is in another service)
        server.expect(requestTo("/v1/s2/dependent-method"))
                .andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(response, MediaType.APPLICATION_JSON));

        return response;
    }
}

Feign客户

@FeignClient(value = "service-s2", url = "http://localhost:8888/")
public interface S2Api {
    @GetMapping("/v1/s2/dependent-method")
    public String dependentMethod();
}

但我得到了以下错误,这意味着这个url没有被存根。

feign.RetryableException: Connection refused: connect executing GET http://localhost:8888/v1/s2/dependent-method
    at feign.FeignException.errorExecuting(FeignException.java:213) ~[feign-core-10.4.0.jar:na]

共1个答案

匿名用户

是的,使用< code > MockRestServiceServer 是可能的。

例子:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;

@RunWith(SpringRunner.class)
@RestClientTest(MyRestClient.class)
@AutoConfigureWebClient(registerRestTemplate = true)
public class MyRestClientTest {
    @Autowired
    private MockRestServiceServer server;

    @Test
    public void getInfo() {
        String response = "response";
        server.expect(requestTo("http://localhost:8090" + "/another/service/call"))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(response,MediaType.APPLICATION_JSON));
    }
}