spring-mvc - Spring MVC 测试用例

标签 spring-mvc junit4 spring-mvc-test

我是 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/

相关文章:

java - 如何在 JSONP 请求中使用 @RequestBody?

java - spring mvc 中的服务层需要什么?推荐什么样的逻辑?

unit-testing - 暂停可取消协程取消的 Kotlin Mockk 测试

junit4 - xtext 参数化 xtext 运行器

spring-boot - SpringBoot junit测试多个TomcatServletContainerInitializer 's - BindException: Address already in use"

apache - Spring Security ajax 登录使用 http 重定向而不是 https

java - 使用 Spring Security 的条件权限实现会是什么样子?

junit4 - Junit 使用模拟对象

xpath - 模拟 HttpServlet 响应 : Checking xml content

Spring 集成测试问题 : could not initialize proxy - no Session through reference chain: