如何编写Junits的类实现球衣的动态功能接口?



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

您需要模拟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是 void 方法,则可以使用示例中的Mockito.doNothing().register(...)
  • 如果register不是 void 方法,请改用Mockito.doReturn(null).register(...)

相关内容

  • 没有找到相关文章

最新更新