Java 我需要为 Jersey Rest Web 服务编写 Junit 测试用例..请帮助我或发布示例代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24822923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:01:36  来源:igfitidea点击:

I need to write Junit Test cases for Jersey Rest web service ..Please help me or post a sample code?

javaunit-testingrestjunitjersey

提问by Rahul Jain

This is the code for which I am looking to write Junit test cases--

这是我希望为其编写 Junit 测试用例的代码——

@GET 

@Path("/get")

@Produces("application/json")

public User getUser() 
{

    User user= new com.rest.rahul.User();

    user.setEmpid("12");
    user.setEmail("[email protected]");
    user.setName("DJ");
    return user;

}

回答by Robin van Breukelen

What do you want to unit test? I wouldn't bother with unit testing simply setters. But if you want to test the JSON output, you're actually looking for something like an an integration test. A test that bootstraps your application, sets up the webservice and then calls the getUsermethod. Take a look at https://blog.codecentric.de/en/2012/05/writing-lightweight-rest-integration-tests-with-the-jersey-test-framework/

你想单元测试什么?我不会打扰单元测试简单的setter。但如果您想测试 JSON 输出,您实际上是在寻找诸如集成测试之类的东西。引导您的应用程序、设置 Web 服务然后调用该getUser方法的测试。看看https://blog.codecentric.de/en/2012/05/writing-lightweight-rest-integration-tests-with-the-jersey-test-framework/

回答by John Papastergiou

Testing a web service with JUnit involves starting up the web service inside the test environment, performing the request, validating the response and then shutting it down.

使用 JUnit 测试 Web 服务涉及在测试环境中启动 Web 服务、执行请求、验证响应,然后将其关闭。

You can use Jersey's REST Client to perform a request on a server that comes up when the test runs. Get the response and Assert your required conditions on the response object.

您可以使用 Jersey 的 REST 客户端在测试运行时出现的服务器上执行请求。获取响应并在响应对象上断言所需的条件。

More on Jersey's client here:

更多关于泽西岛客户的信息:

http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/