我是 Spring MVC 的新手,我使用 spring MVC 和 Resteasy 编写了 Web 服务。我的 Controller 工作正常,现在需要编写测试用例,但我尝试编写,但从未成功,而且在 Autowiring 方面也遇到问题。
@ Controller
@Path("/searchapi") public class SearchAPIController implements ISearchAPIController { @Autowired private ISearchAPIService srchapiservice; @GET @Path("/{domain}/{group}/search") @Produces({"application/xml", "application/json"}) public Collections getSolrData( @PathParam("domain") final String domain, @PathParam("group") final String group, @Context final UriInfo uriinfo) throws Exception { System.out.println("LANDED IN get****************"); return srchapiservice.getData(domain, group, uriinfo); } }
任何人都可以给我 spring mvc 中测试用例的示例代码吗?
最佳答案
使用模拟对象的“Spring-MVC”测试用例可能看起来像这样,例如我们要测试我的 MyControllerToBeTest:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring.xml")
public class MyControllerTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MyControllerToBeTested controller;
private AnnotationMethodHandlerAdapter adapter;
@Autowired
private ApplicationContext applicationContext;
@Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
controller = new MyControllerToBeTested();
adapter = new AnnotationMethodHandlerAdapter();
}
@Test
public void findRelatedVideosTest() throws Exception {
request.setRequestURI("/mypath");
request.setMethod("GET");
request.addParameter("myParam", "myValue");
adapter.handle(request, response, controller);
System.out.println(response.getContentAsString());
}
}
但我没有任何 REST 资源测试经验,在你的例子中是 RestEasy。
关于spring-mvc - Spring MVC 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963976/