使用 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 对象变为 null 并出现 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 上下文中设置模拟.

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));

相关文章