【发布时间】:2017-08-26 00:06:29
【问题描述】:
我有一个使用 Spring MVC 运行 REST 服务的应用程序(没有 Spring Boot)。上下文主要是从父母那里加载的。 我有一个控制器,我想通过 MockMVC 对其进行测试。
我曾尝试手动设置本地测试上下文,但这还不足以运行测试。我想,应该还有我没有设置的额外 bean。
我的控制器是:
@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
并且没有创建任何bean
PS有一个选项可以使用
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
但是,它需要重构控制器方法,这是不可能的
【问题讨论】:
标签: java rest spring-mvc mockito spring-test-mvc