我有一個應用程序使用Spring MVC運行REST服務(沒有Spring Boot)。上下文主要由父節點加載。 我有一個控制器,我想通過MockMVC進行測試。SpringBoot應用程序之外使用MockMVC
我試圖用手設置本地測試上下文,但它不足以用於運行測試。我想,應該有額外的豆我沒有建立。
我的控制器:
@RestController
public class ProrertyEditorController extends AbstractPropertyEditorController {
@Autowired
protected PropertyEditorService prorertyEditorService;
@RequestMapping(method = RequestMethod.DELETE, value = "/{dataType}/deletewithcontent")
@ResponseStatus(value = HttpStatus.OK)
public void deleteWithContent(@PathVariable("dataType") String dataType, @RequestParam("deleteall") boolean deleteAllContent, @RequestBody String node) {
try {
JSONArray itemsToDelete = new JSONArray(node);
prorertyEditorService.deleteItemsWithContent(dataType, itemsToDelete, deleteAllContent);
} catch (Exception e) {
//handling exception
}
}
直至目前爲止,測試控制器看起來是這樣的:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath*:configBeans1.xml")
public class ProrertyEditorControllerTest{
private MockMvc mockMvc;
@Mock
private PropertyEditorService mockService;
@InjectMocks
private ProrertyEditorController controller;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(new ProrertyEditorController()).build();
}
@Test
public void deleteWithContentTest() throws Exception {
mockMvc.perform(delete("/full/path/{dataType}/deletewithcontent", type)
.param("deleteall", "true")
.param("node", "[{\"test key1\":\"test value1\"}, {\"test keys2\":\"test value2\"}]"));
verify(mockService, times(1)).deleteItemsWithContent(eq("promotion"), eq(new JSONArray("[{\"test key1\":\"test value1\"}, {\"test keys2\": \"test value2\"}]")), eq(true));
}
不幸的是,這是行不通的,由於
Failed to load ApplicationContext
並沒有創建豆子
PS還有就是用
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
但是一個選項,它需要控制器方法的重構,這是不可能的