【发布时间】:2020-04-21 23:40:02
【问题描述】:
我继承了一个不包含 ApplicationContext xml 文件并且似乎没有在应用程序中使用 ApplicationContext 的旧版应用程序。当我尝试测试时抛出以下异常:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at
该应用程序是一个 Spring 应用程序并且确实包含一个控制器:
@Controller
public class DataController {
但我不确定如何在没有 applicationContext 文件的情况下测试控制器服务。
这是我的测试类,它抛出java.lang.IllegalStateException:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.ModelAndViewAssert;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import javax.inject.Inject;
//@ContextConfiguration({/* include live config here
// e.g. "file:web/WEB-INF/application-context.xml",
// "file:web/WEB-INF/dispatcher-servlet.xml" */})
@RunWith(SpringJUnit4ClassRunner.class)
public class CustomTest {
@Inject
private ApplicationContext applicationContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private ReviewController controller;
@Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
// I could get the controller from the context here
controller = new DataController();
}
@Test
public void testFoo() throws Exception {
request.setRequestURI("/data/get");
final ModelAndView mav = handlerAdapter.handle(request, response,
controller);
}
}
如何使用签名测试DataController.getData 方法:
@RequestMapping(value = "/data/get", method=RequestMethod.GET)
public void getData(HttpServletResponse response, @PathVariable("dataId") long id) {
?
【问题讨论】:
标签: java spring servlets mocking