我有一个应用程序使用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();
但是一个选项,它需要控制器方法的重构,这是不可能的