我遇到了用mockito + junit编写的测试用例 在这里找到相同的帮助。方案如下
Class Application{
//property 1
//property 2
ForeignCollection<Key> keys; //Key class contains multiple keys for same application id and this field does not exist in application Table
}
这是我想要创建我的测试用例的方法
class ClassService{
public Response method(Request request){
//some lines of code
verifyKey(request,Application app); //a private method of same class
}
private void verifyKey(Request r,Application a){
boolean matched = false;
Iterable<Key> keys = application.getSecretKeys().getWrappedIterable();
for(Key key : keys )
if(request.headers("Key").equals(key.getKey())) secretKeyMatched=true;
if(!secretKeyMatched) throw new InvalidSecretKeyException(request.headers("Secret-Key"),"INVALID SECRET KEY");
}
}
以下是测试用例
Class TestClass{
@Mock
private ForeignCollection<Key> keyForeignCollection;
@Mock
Request request;
@Mock
Response response;
@Mock
ClassService classService;
//below are not mocked
private CloseableWrappedIterable<Key> closeableWrappedIterableOfKey;
private Iterable<Key> IterableOfKey;
@Before
public void setUp(){
keyForeignCollection.add(Key object);
keyFoerignCollection.add(Key object);
}
public void shouldMethod(){
keyForeignCollection.add(make(a(keyMaker.ApplicationSecretKey)));
application.setkeys(keyForeignCollection);
when(applicationSecretKeyForeignCollection.size()).thenReturn(2);
when(application.getKeys().getWrappedIterable()).thenReturn(closeableWrappedIterableOfKey);
when(request.headers("Key")).thenReturn("some-key"); when(application.getKeys().getWrappedIterable()).thenReturn(keyForeignCollection.getWrappedIterable());
//
Response response = clasService.method(request);
Map<String, String> responseBody = (Map<String, String>) response.getBody();
}
}
每当从测试用例调用该方法时,由于调用内部方法即验证(Request,Application),它会抛出空指针异常;
帮助!
答案 0 :(得分:1)
假设您的目标是绕过对verifyKey方法的调用,而不是测试它;你可以use a Spy。使用@Spy
注释classService并模拟ClassService :: verifyKey(Request,Application)方法。
要模拟一个void方法,只需编写
Mockito.doNothing().when(classService ).verifyKey(x, y);