单元测试spring webservice客户端类继承WebServiceGatewaySupport

时间:2019-01-11 20:42:59

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

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

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

快速搜索仅说明有关使用spring的集成测试的信息,这不是我所需要的 [link]

在S / O中,已经建议模拟整个基类,但是由于单元测试在同一包中,而且我也不想手动模拟spring类,所以不可能。

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

1 个答案:

答案 0 :(得分:0)

您可以使用@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());
   }