【问题标题】:Unit testing spring webservice client Classes Inheriting WebServiceGatewaySupport单元测试spring webservice客户端类继承WebServiceGatewaySupport
【发布时间】:2019-01-11 20:42:58
【问题描述】:

我正在尝试在 Spring Boot 中对 Web 服务客户端进行单元测试。我的客户扩展了 WebServiceGatewaySupport 类,我正在使用 Mockito 框架。

问题是我无法模拟超类方法getWebServiceMethod

快速搜索只解释了使用spring的集成测试,这不是我需要的 [link]

在 S/O 中,有人建议模拟整个基类,但这也不可能,因为单元测试在同一个包中,而且我不想手动模拟 spring 类。

我了解composition over inheritance,但这是违反此规定的有效用例吗?在这些情况下,我们如何实现此单元测试?

【问题讨论】:

  • 你考虑过使用间谍对象吗?

标签: java spring unit-testing spring-boot mockito


【解决方案1】:

你可以通过@AutoConfigureMockMvc来使用springboot内部的tomcat

import javax.servlet.http.Cookie;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
// plus some other that I skip for sake of simplicity


@RunWith(SpringRunner.class)
@SpringBootTest(classes = StandaloneApplication.class) // StandaloneClass is where you call SpringApplication.run
@AutoConfigureMockMvc
public class DictionaryControllerTest  {
   private final static ObjectMapper mapper = new ObjectMapper();

   @Test
   public void createDictionary() throws Exception {
       Cookies cookies;  // add cookies if you need
       String body; // add a body if you need
       MockHttpServletRequestBuilder request = requestBuilder(post("/dictionaries"), body, cookies);
       ResultActions resultActions = mockMvc.perform(request);
       // you can also extract the content
       CollectionDocument dictionary = mapper.readValue(resultActions.andReturn().getResponse().getContentAsString(), CollectionDocument.class);
       // then do the test
       Assert.assertNotNull(dictionary.getId());
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2013-12-07
    • 2021-08-10
    相关资源
    最近更新 更多