在Spring引导框架中,我发现使用JUnit和Mockito进行控制器单元测试很困难。我想测试这种方法。如何测试DELETE请求方法:
//删除应用程序 控制器类
@DeleteMapping("/applications")
public String deleteApplicationByObject(@RequestBody Application application) {
applicationService.deleteById(application.getId());
return "Deleted";
}
//删除应用程序 服务等级
@Override
@Transactional
public String removeById(Long id) {
dao.deleteById(id);
return "SUCCESS";
}
//删除应用程序 道课
@Override
public void deleteById(Long id) {
Application application = findById(id);
em.remove(application);
}
谢谢。
答案 0 :(得分:1)
一段时间后,我能够找到我的问题的解决方案,
ApplicationControllerTest.class
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());
}