如何为实现jersey动态特性接口的类编写junits?

disho6za  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(322)

1.如何使用mockito为这个类编写junit?

public class Jerseybinding implements DynamicFeature{

    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        if (SomeImpl.class.equals(resourceInfo.getResourceClass()) || SomeResource.class.equals(resourceInfo.getClass())) {
            context.register(new ExampleFilter(new ExampleMatcher()));
        }
    }

}

我已经编写了junit,但是当我试图返回someresource.class时,它抛出了错误。

public class JerseybindingTest { 
  public void before(){ 
    resourceInfo = Mockito.mock(ResourceInfo.class); 
    info = Mockito.mock(UriInfo.class); 
    featureContext = Mockito.mock(FeatureContext.class); 
  } 
  @Test 
  public void testBind() {     
    Mockito.when(resourceInfo.getClass()).thenReturn(SomeResourc‌​e.class); // this line also shows error when I return anything.class
    Mockito.when(featureContext.register(Mockito.class)).thenRet‌​urn(featureContext);‌​// same here 
    Jerseybinding.configure(resourceInfo,featureContext);
  }
}
zi8p0yeb

zi8p0yeb1#

你得模仿一下 FeatureContext 并Assert register 按预期调用。
大致如下:

@Test
public void testConfigure() {
  SomeImpl resourceInfo = ... ; // create a new instance of SomeImpl, or mock it if needed

  // prepare your mock
  FeatureContext context = Mockito.mock(FeatureContext.class);
  Mockito.doNothing().when(context).register(Mockito.any(ExampleFilter.class));

  // invoke the method under test
  JerseyBinding binding = new JerseyBinding();
  binding.configure(resourceInfo, context);

  // verify that we called register
  Mockito.verify(context).register(Mockito.any(ExampleFilter.class));

  // verify nothing else was called on the context
  Mockito.verifyNoMoreInteractions(context);
}

或者,如果您想验证传递到 register 方法。
如果 register 是一个void方法,可以使用 Mockito.doNothing().register(...) 如示例所示。
如果 register 不是void方法,请使用 Mockito.doReturn(null).register(...) 相反。

相关问题