标签: jersey-test-framework

JerseyTest在Jersey 2.13中使用GrizzlyWebTestContainerFactory

我试图让JerseyTest运行使用org.glassfish.jersey.test.grizzly.GrizzlyWebContainerFactory.我已经搜索了互联网,并在一天中的大部分时间里尝试了几件事.这似乎是不可能的,我真的很感激有关如何启动和运行的任何帮助.

我根据Jersey 2文档中的代码创建了一个最小的示例.代码如下:

package test;

import static org.junit.Assert.assertEquals;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;

public class DistributedDeploymentTest extends JerseyTest {

@Path("hello")
public static class HelloResource {
    @GET
    public String getHello() {
        return "Hello World!";
    }
}

@Override
protected Application configure() {
    return new ResourceConfig(HelloResource.class);
}

@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    return new GrizzlyWebTestContainerFactory();
}

@Override
protected DeploymentContext configureDeployment() {
    return …
Run Code Online (Sandbox Code Playgroud)

java jax-rs jersey jersey-2.0 jersey-test-framework

9
推荐指数
1
解决办法
8719
查看次数

在JerseyTest中找不到媒体类型= multipart/form-data的MessageBodyWriter

我正在尝试为POSTJersey程序中的资源类中的方法创建一个测试.

这是POST资源的方法:

@POST @Path("/new")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response HTTPPostMethod(@FormDataParam("file") InputStream fileIS, 
                           @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {
    // ... some code that handles the InputStream
}
Run Code Online (Sandbox Code Playgroud)

ResourceConfig的创建方式如下:

public class MyApp extends ResourceConfig {

    public MyApp(String param) {
        register(createMoxyJsonResolver());     
        register(MultiPartFeature.class);
        register(MyResource.class);
    }

     private static ContextResolver<MoxyJsonConfig> createMoxyJsonResolver() {
        final MoxyJsonConfig moxyJsonConfig = new MoxyJsonConfig();
        Map<String, String> nsPrefixManager = new HashMap<String, String>(1);
        nsPrefixManager.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
        moxyJsonConfig.setNamespacePrefixMapper(nsPrefixManager).setNamespaceSeparator(':');
        return moxyJsonConfig.resolver();
    }

    /**
     * Start the Grizzly HTTP Server
     * 
     */
    public final void …
Run Code Online (Sandbox Code Playgroud)

java testing multipartform-data jersey jersey-test-framework

8
推荐指数
1
解决办法
7223
查看次数

如何让Jersey Test/Client不填写默认的Accept标头?

我正试图以Accept一种特定的方式处理一个没有标题的请求,但是不管我做什么,泽西岛似乎都在努力填写一个请求,所以它总是看起来像请求有一个Accept标题,即使它没有.

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;

import static org.junit.Assert.assertEquals;

public class JerseyTestTest extends JerseyTest {

    @Path("hello")
    public static class HelloResource {
        @GET
        public String getHello(@Context HttpHeaders httpHeaders) {
            String acceptHeader = httpHeaders.getHeaderString(HttpHeaders.ACCEPT);
            return acceptHeader != null ? acceptHeader : "No Accept Header";
        }
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(HelloResource.class);
    }

    @Test
    public void test() {
        final String hello = target("hello").request()
                .header(HttpHeaders.ACCEPT, null) …
Run Code Online (Sandbox Code Playgroud)

java jersey jersey-client jersey-test-framework

7
推荐指数
1
解决办法
993
查看次数

使用泽西测试框架模拟服务内部资源

我有一个使用服务的rest API资源.此服务具有带参数的构造函数.我想测试这个资源并模拟这个服务.这个问题:如何通过使用泽西2.5参数REST资源

没用,因为他们使用了@Inject而我无法使用它.有什么建议?

第二个问题是我如何传递参数来测试这个资源:我的代码是:

@Path("/2/{subversion: [0-3]}/users")
public class UserResource {
    Logger log = Logger.getLogger(UserResource.class);
    private MyService service;
    public void setService(Service ser) {
        this.service = ser;
    }
Run Code Online (Sandbox Code Playgroud)

@Context HttpServletRequest currentRequest;

@GET
@Produces("application/json")
public Response getUsers(@Context HttpHeaders httpHeaders, @Context UriInfo
uriInfo) {
// my function
}
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能传递"httpHeaders"和"UriInfo".我的测试看起来像这样:

Response response = target("/2/0/users/").request().get();
Users users = response.readEntity(Users.class);
assertNotNull(users);
Run Code Online (Sandbox Code Playgroud)

java rest unit-testing jersey-2.0 jersey-test-framework

6
推荐指数
1
解决办法
7728
查看次数

在JUnit测试期间,静态初始化程序不会运行

我在这里有一个有趣的JUnit问题(JUnit 4.12).我有一个只有静态方法的基类.它们必须是静态的,因为它们的使用方式.我从基类继承了其他类.所以,如果基类是Base,我们有ChildAChildB.

大多数方法都包含在基类中,但它必须知道它实际上是哪个子项(只是调用方法,因为基类是无效的).这是通过基类中的静态数据成员完成的:

public class Base {

    protected static ChildType myType = ChildType.Invalid;
    ...
}    
Run Code Online (Sandbox Code Playgroud)

每个子项都通过静态初始化程序设置数据成员,因此:

static {
    myType = ChildType.ChildA;
}
Run Code Online (Sandbox Code Playgroud)

然后,当调用方法时,基类知道它是什么类型并加载适当的配置(类型实际上是配置名称).

这一切都在运行应用程序时完美运行.在调试器和日志消息中逐步执行它,我可以看到设置了适当的类型,并且方法根据子类型加载适当的配置.

使用JUnit时出现问题.我们有一些JUnit测试来测试每个基类方法.由于仅在基类上调用方法无效,因此我们在子类上调用方法,因此:

bool result = ChildA.methodTwo();
Run Code Online (Sandbox Code Playgroud)

这''总是失败''.为什么?永远不会调用静态初始化程序.将代码作为应用程序运行时,它会被调用,每个人都很高兴.当我将其作为JUnit测试运行时,将跳过静态初始化程序,并且方法具有无效数据.什么是JUnit跳过静态初始化程序?有办法解决吗?

细节

实际上,我们没有像上面发布的那样调用方法.我只想让这个例子尽可能清楚.实际上,我们有一个用Jersey框架编写的Web服务.调用的方法是REST端点之一.

@POST
@Produces(MediaType.TEXT_PLAIN)
public String methodPost() {
    ...
    return new String( itWorked ? "success" : "fail" );
}
Run Code Online (Sandbox Code Playgroud)

我们这样称呼它(对于丑陋的语法感到抱歉,这只是它的工作方式):

@Test
public void testThePost() throws Exception {

    javax.ws.rs.core.Response response = target("restapi/").request().post(Entity.entity(null, MediaType.TEXT_PLAIN));

    assertEquals( 200, response.getStatus() );
}
Run Code Online (Sandbox Code Playgroud)

所有GET测试都可以工作,并且所有这些测试都会调用静态初始化程序.只是这个POST失败了,只有在运行JUnit测试时才会失败.

java unit-testing junit4 jersey-test-framework

6
推荐指数
2
解决办法
887
查看次数

如何在测试类中为所有测试启动Jersey测试容器(Grizzly)一次?

我正在努力修复其中一个项目中的集成测试.目前,所有集成测试类都扩展了JerseyTest类.通过JerseyTest类,我意识到它使用Junit的Before和After注释为每个测试方法启动和停止容器.

为什么这有必要?如果我们提起容器一次,运行测试并在结束时将其关闭,这还不够吗?

我们也使用Spring,上下文初始化需要时间.

在Junit4之前,我们通过使用布尔标志手动处理它来解决这个限制.

@Before
public void setup() {
  if(!containerStarted) {
   // start
   containerStarted = true;    
  }
 // else do nothing
}
Run Code Online (Sandbox Code Playgroud)

java junit jersey jersey-2.0 jersey-test-framework

5
推荐指数
1
解决办法
5059
查看次数

Jersey客户端API vs Jersey测试框架

我是Web服务的新手,想知道Jersey客户端API和球衣测试框架有什么区别?

我想测试我的球衣REST网络服务端点.哪个是正确的?

java rest jersey jersey-client jersey-test-framework

4
推荐指数
1
解决办法
1万
查看次数

Jackson LocalDate/Time 反序列化

我配置了 jackson 以便它给我一个简单的字符串表示 ifjava.time.LocalDatejava.time.LocalDateTime。这可以在序列化过程中找到,例如当我在 REST api 上获取数据时。

不过反过来也行不通。当我尝试将数据发送到服务器并且 JSON 应该被解析为 java 对象时,会抛出此异常:

javax.ws.rs.client.ResponseProcessingException: com.fasterxml.jackson.databind.JsonMappingException: 无法构造 java.time.LocalDateTime 的实例: 没有从字符串值反序列化的字符串参数构造函数/工厂方法 ('2018-04- 19T14:10:30.903')

经过几个小时的研究,我设法让它工作,但仅限于我分别用@JsonDeserialize(using = LocalDateDeserializer.class)或注释的属性@JsonDeserialize(using = LocalDateTimeDeserializer.class)

在我看来,如果我可以在一个中心位置定义这些映射,那将是理想的。

ObjectMapper 配置:

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
    @Override
    public ObjectMapper getContext(Class<?> aClass) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        return mapper;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试向 JavaTimeModule 添加自定义反序列化器,但没有成功:

JavaTimeModule dateTimeModule = new JavaTimeModule();
dateTimeModule.addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE);
dateTimeModule.addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);

mapper.registerModule(dateTimeModule);
Run Code Online (Sandbox Code Playgroud)

长话短说:有没有办法全局定义映射,这样我就不需要在每个字段上添加这些注释。谢谢!

编辑:

好的:我用邮递员测试了它,没有注释,它按预期工作。但是,当我运行单元测试 (JerseyTest) 时,它会抛出上述异常。我将 …

java jersey jersey-test-framework jackson2

4
推荐指数
1
解决办法
3062
查看次数

JerseyTest 默认端口更改以测试 REST WEB SERVICE

我做了一个测试用例来测试我的 Rest Web 服务。但在测试用例中,我看到请求将发送到 jersey 测试框架的默认端口, http://localhost:9998而我的服务在http://localhost:8080. 我找不到如何将其端口更改为8080

public class UMServiceTest extends JerseyTest {


    @Override
    public Application configure() {
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        return new ResourceConfig(UMService.class);
    }    


    @Test
    public void testFetchAll() {
        System.out.println(getBaseUri()+"==========");
        Response output = target("usermanagement").path("um").path("user").request().get();
        assertEquals("should return status 200", 200, output.getStatus());
        //assertNotNull("Should return list", output.getEntity());
    }
Run Code Online (Sandbox Code Playgroud)

java rest web-services jersey-test-framework jakarta-ee

3
推荐指数
2
解决办法
1984
查看次数

Jersey测试 - 不调用ExceptionMapper

我有REST网络服务,我用Jersey Test,Mockito,Junit测试.成功执行Web服务方法后,我得到正确的响应.如果数据无效,则抛出自定义异常,必须由ExceptionMapper处理.它应该返回相同的结构响应,但具有不同的代码.ExceptionMapper在非测试环境中运行良好.但是,测试执行日志显示后:

1 < 500
1 < Connection: close
1 < Content-Length: 1033
1 < Content-Type: text/html;charset=ISO-8859-1
1 < Date: Wed, 30 Mar 2016 11:55:37 GMT

javax.ws.rs.InternalServerErrorException: HTTP 500 Request failed.
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1020)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:816)
at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
Run Code Online (Sandbox Code Playgroud)

我用:

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>2.22.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

缩短版的模拟服务,由测试类扩展:

public class MockedService extends JerseyTest {

    @Override
    public ResourceConfig configure() {

        forceSet(TestProperties.CONTAINER_PORT, "8080");
        enable(TestProperties.LOG_TRAFFIC);

        return new ResourceConfig().register(new Service());
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从ExceptionMapper获取响应?

junit jersey mockito exceptionmapper jersey-test-framework

2
推荐指数
1
解决办法
2299
查看次数

JerseyTest框架路径编码替换了吗?与%3F

我的考试不及格,应该通过。该服务运行正常,但是JerseyTest JUnit测试失败,状态为400。

当我针对已部署的服务尝试使用此URL时,使用Postman或浏览器:

http://localhost:8080/myService/123?appId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)

我得到正确的结果,状态为200,并在日志中看到以下内容:

    INFO: 4 * Server has received a request on thread http-nio-8080-exec-5
4 > GET http://localhost:8080/myService/123?appId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)

注意?在URL中,这是正确的。

但是,当我在JeryseyTest扩展的Junit类中尝试此单元测试时:

@Test
public void getWithCorrectUrlExecutesWithoutError()
{
    String x = target("myService/123?appId=local&userId=jcn").request().get(String.class);
}
Run Code Online (Sandbox Code Playgroud)

它失败并显示状态400,我在日志中看到了这一点:

INFO: 1 * Server has received a request on thread grizzly-http-server-0
1 > GET http://localhost:9998/myService/123%3FappId=local&userId=jcn
Run Code Online (Sandbox Code Playgroud)

注意吗?已被%3F取代。

我不明白发生了什么。如果在浏览器中尝试“%3F” URL,则单元测试中会看到相同的400错误。因此,我可以肯定地确定url的编码是问题所在。

这是我的Jersey资源,部分列出,因为它很长,但是我很确定这是相关的部分:

    @Component
    @Path("/myService")
    public class MyResource
    {
        @Autowired
        SomeDao someDao;

        @NotBlank
        @QueryParam("appId")
        private String appId;

        @NotBlank
        @QueryParam("userId")
        private String userId;


        @GET
        @Path("/{id}")
        @Produces(MediaType.APPLICATION_JSON)
        public Status getStatus(@NotBlank @PathParam("id") String id) …
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing jersey jersey-test-framework

0
推荐指数
1
解决办法
1019
查看次数

如何使用 JerseyTest 依赖限定符模拟注入值

我正在尝试模拟包括 jax-rs 层的控制器/资源。该类具有需要注入的依赖项。然而,它也有一些String使用限定符接口注入的值。

基本上,我使用 JerseyTest 运行单个控制器并使用 HK2 进行依赖项注入。我创建了一个ResourceConfig并注册了一个AbstractBinder来绑定注入的类。

这对于常规注入的依赖项来说效果很好,但是当@SomeQualifierInterface添加附加注释时,它会崩溃并出现以下错误:

MultiException stack 1 of 3
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=String,parent=ThingsController,qualifiers={@com.company.SomeQualifierInterface()},position=-1,optional=false,self=false,unqualified=null,10035302)
  ...
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.company.ThingsController errors were found
  ...
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on com.company.ThingsController
  ...

Run Code Online (Sandbox Code Playgroud)

请参阅下面简化的完整代码示例:

控制器/资源

MultiException stack 1 of 3
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection …
Run Code Online (Sandbox Code Playgroud)

java mockito hk2 jersey-test-framework jakarta-ee

0
推荐指数
1
解决办法
1596
查看次数