How to test DELETE method in Spring boot using Mockito and JUnit
在 Spring Boot 框架中,我发现使用 JUnit 和 Mockito 进行控制器单元测试的困难。我想测试这个方法。如何测试 DELETE 请求方法:
// 删除应用程序
控制器类
1 2 3 4 5 | @DeleteMapping("/applications") public String deleteApplicationByObject(@RequestBody Application application) { applicationService.deleteById(application.getId()); return"Deleted"; } |
// 删除应用程序
服务类
1 2 3 4 5 6 |
// 删除应用程序
道类
1 2 3 4 5 | @Override public void deleteById(Long id) { Application application = findById(id); em.remove(application); } |
提前谢谢你。
过了一会儿,我能够找到我的问题的解决方案,
ApplicationControllerTest.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package com.spring.addapplication.test.controller; import static org.mockito.MockitoAnnotations.initMocks; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.fasterxml.jackson.databind.ObjectMapper; import com.spring.addapplication.controller.ApplicationController; import com.spring.addapplication.model.Application; import com.spring.addapplication.service.ApplicationService; import com.spring.addapplication.url.UrlChecker; @RunWith(SpringJUnit4ClassRunner.class) public class ApplicationControllerTest { @Mock ApplicationService applicationService; private MockMvc mockMvc; @Before public void setUp() throws Exception { initMocks(this);// this is needed for inititalization of mocks, if you use @Mock ApplicationController controller = new ApplicationController(applicationService,urlChecker); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test public void deleteApplication() throws Exception { Mockito.when(applicationService.removeById(10001L)).thenReturn("SUCCESS"); mockMvc.perform(MockMvcRequestBuilders.delete("/applications", 10001L)) .andExpect(status().isOk()); } |