概述
在日常的開發中,我們一般會定義一個service
層,用于實現業務邏輯,并且針對service
層會有與之對應的齊全的覆蓋率高的單元測試。而對于controller
層,一般不怎么做單元測試,因為主要的核心業務邏輯都在service
層里,controller
層只是做轉發,調用service
層接口而已。但是還是建議使用單元測試簡單的將controller
的方法跑一下,看看轉發和數據轉換的代碼是否能正常工作。
在Spring Boot
里對controller
層進行單元測試非常簡單,只需要幾個注解和一點點輔助代碼即可搞定。
依賴的包
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency>
使用的Spring Boot 版本
2.0.4.RELEASE
代碼
@ExtendWith(SpringExtension.class)@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)@AutoConfigureMockMvcpublic class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test @DisplayName("測試controller方法") void test() throws Exception { User param = new User(); param.setUserId(1111); List<Address> addressList = new ArrayList<>(); Address address = new Address(); address.setName("我的地址"); addressList.add(address); param.setAddressList(addressList); MvcResult mvcResult = mockMvc.perform( post("/xxx/test") .contentType(MediaType.APPLICATION_JSON) .content(JSON.toJSONString(param))) .andReturn(); System.out.println(mvcResult.getResponse().getContentAsString()); }}
@RequestMapping(value = "/xxx", method = RequestMethod.POST)public Object test(@RequestBody(required = false)User user) throws Exception {}
如果你只是想簡單的跑一下controller
層,不想真正的去執行service
方法的話,需要使用@MockBean
將對應的service
類mock
掉。
@MockBean private UserService userService;
使用Spring Boot Test
的時候,它需要一個ApplicationContext
,我們可以在@SpringBootTest
注解中使用classes
屬性來指定。
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.MOCK,classes = TestApplication.class)
TestApplication
的代碼很簡單。
@SpringBootApplicationpublic class TestApplication { public static void main(String[] args){ SpringApplicationBuilder builder = new SpringApplicationBuilder(); builder.environment(new StandardEnvironment()); builder.sources(TestApplication.class); builder.main(TestApplication.class); builder.run(args); }}
接下來我們只需要使用MockMvc
發送post
請求即可。如果controller
層的post
方法是帶@RequestBody
注解的,可以先將入參對象轉換成JSON
字符串。這里使用的是fastjson
。
JSON.toJSONString(param)
經過測試,如上代碼能正常工作。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選