使用Jersey Rest测试框架和Mockito进行单元测试 [英] Unit Testing with Jersey Rest Test Framework and Mockito

查看:841
本文介绍了使用Jersey Rest测试框架和Mockito进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我解决这个问题。
我正在使用Jersey rest测试框架版本2.21编写Rest资源的单元测试。(在Grizzly容器上)。

Could someone help me on this. I am writing Unit test for Rest resource using Jersey rest test framework version 2.21.(On Grizzly container).

当我调试测试类时,我看到了myManager的模拟对象。但是当调试进入我的MyResouce类时,myManager对象变为空并获得NullPointer异常。

When I debug the test class, am seeing mock object for myManager . But when the debug enters my "MyResouce class, myManager object is becoming null and getting NullPointer Exception.

尝试过不同的人提供的解决方案,但没有运气。可以有人请帮帮我。几乎三天就遇到了这个问题。:(

Have tried with solutions given by different people, but no luck.Could someone help me please. Am with this problem from almost three days. :(

我的资源类是这样的。

@Component
@Path("/somepath")
public class MyResource {
    @Autowired
    private MyManager myManager;

    @Path("/somepath")
    @GET
    @Produces("application/json")
    @ResponseType(String.class)
    public Response getResults(@QueryParam("queryParam") String number) {
        // myManager is an interface
        String str = myManager.getResult(number);
    }
}

这是我的测试类

public class MyResourceTest extends JerseyTest {
    @Mock
    private MyManager myManager;

    @InjectMocks
    private MyResource myResource;

    @Override
    protected Application configure() {
        MockitoAnnotations.initMocks(this);
        return new ResourceConfig().register(MyResource.class)
                .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bind(myManager).to(MyManager.class);
                    }
                });
    }

    @Test
    public void getResultsTest() {
        when(myManager.getResult(anyString())).thenReturn(mock(String.class));
        String str = target("path").queryParam("queryParam","10").request().get(String.class);
    }
}


推荐答案

你'使用Spring(注入)注释,因此将从spring上下文中查找服务。这就是为什么它是null,因为你没有在spring上下文中设置mock。

You're using Spring (injection) annotations, so the service will be looked up from the spring context. That's why it's null, because you haven't set up the mock in the spring context.

最好的办法是使用构造函数注入(而不是字段注入) 。这使得测试变得更加容易

The best thing to do is to use constructor injection (instead of field injection). This makes testing a lot easier

@Path(..)
public class MyResource {
    private final MyManager manager;

    @Autowired
    public MyResource(MyManager manager) {
        this.manager = manager;
    }
}

然后在你的测试中

return new ResourceConfig()
    .register(new MyResource(myManager));

这篇关于使用Jersey Rest测试框架和Mockito进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆