如何为实现泽西动态特征界面的类编写Junits?

时间:2017-07-14 19:20:57

标签: java junit jersey mockito

1.如何使用mockito为这个班级编写junits?

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

1 个答案:

答案 0 :(得分:0)

您需要模拟FeatureContext并断言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方法的内容的详细信息,您也可以使用ArgumentCaptor。

  • 如果register是无效方法,则可以使用Mockito.doNothing().register(...),如示例所示。
  • 如果register不是空方法,请改用Mockito.doReturn(null).register(...)