小编min*_*ate的帖子

使用Guice注入字段对泽西资源进行单元测试

我有一个泽西资源,我想用JUnit测试.该资源使用Guice Providers注入某些字段:

@Path("/example/")
class ExampleResource {
    @Inject
    Provider<ExampleActionHandler> getMyExampleActionHandlerProvider;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<ExamplePojo> getExampleList() {
        ExampleActionHandler handler = getMyExampleActionHandlerProvider.get();
        handler.doSomething();
    ...
Run Code Online (Sandbox Code Playgroud)

当使用真实服务器为API提供服务时,这一切都很有效,但测试它是有问题的.

我的测试类目前看起来像:

public class ApiTest extends JerseyTest {

  public ApiTest() throws Exception {
    super();
    ApplicationDescriptor appDescriptor = new ApplicationDescriptor();
    appDescriptor.setContextPath("/api");
    appDescriptor.setRootResourcePackageName("com.my.package.name");
    super.setupTestEnvironment(appDescriptor);
  }

  @Test
  public void testHelloWorld() throws Exception {
    String responseMsg = webResource.path("example/").get(String.class);
    Assert.assertEquals("{}", responseMsg);
  }
}
Run Code Online (Sandbox Code Playgroud)

显然,Guice没有机会初始化字段,ExampleResource因此handler.doSomething()调用不会导致NullPointerException.

有没有办法告诉Jersey使用Guice实例化ExampleResource类,以便提供程序工作?

java junit jersey guice

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

单元测试gwt-dispatch

我正在尝试使用JUnit为gwt-dispatch服务编写一些单元测试.使用我的调试器逐步完成测试时出现以下错误:

自定义提供程序出错,com.google.inject.OutOfScopeException:无法访问作用域对象.我们当前不在HTTP Servlet请求中,或者您可能忘记将com.google.inject.servlet.GuiceFilter应用为此请求的servlet过滤器.

我将在这里简化代码 - 希望我没有删除任何必要的东西.

import junit.framework.TestCase;
import net.customware.gwt.dispatch.client.standard.StandardDispatchService;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.ServletModule;
...

public class LoggedInServiceTest extends TestCase {

Injector i;
StandardDispatchService service;

protected com.google.inject.Injector getInjector() {
    return Guice.createInjector(new ServletModule(),
            new TestServletModule(),
            new ActionsHandlerModule(),
            new TestDispatchModule(),
            new OpenIdGuiceModule());

}

public void setUp() throws Exception {
    i = getInjector();
    service = i.getInstance(StandardDispatchService.class);
}

public void testNotLoggedIn() {
    try {
        GetProjectsResult result = (GetProjectsResult) service.execute(new GetProjectsAction());
        result.getSizeOfResult();
    } catch (Exception e) {
        fail();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

服务请求确实应该通过GuiceFilter,看起来没有设置过滤器.

有关注册过滤器需要做什么其他设置的任何想法?

java gwt google-app-engine junit guice

3
推荐指数
1
解决办法
1855
查看次数

标签 统计

guice ×2

java ×2

junit ×2

google-app-engine ×1

gwt ×1

jersey ×1