因此,我对代码进行了一些分解,使其更通用,也更容易让其他人理解类似的问题
这是我的主要代码:
protected void methodA(String name) {
Invocation.Builder requestBuilder = webTarget.request();
requestBuilder.header(HttpHeaders.AUTHORIZATION, authent.getPassword());
response = request.invoke();
if (response.equals("unsuccessfull")) {
log.warn("warning blabla: {} ({})");
} else {
log.info("info blabla {}");
}
}
}
}
而我的测试代码如下所示:
@Test
public void testMethodA() throws Exception {
final String name = "testName";
this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
assertEquals(1, logger.infos.size());
}
正如我所说,代码更复杂,我将其分解并使其更短......希望它仍然可读。
我的问题不是我的 when().thenReturn()
不起作用,因此我的代码无法进一步进行......我想我的模拟无法正常工作出于某种原因。
最佳答案
您测试 methodA()
方法,但模拟 Authent
类并在调用测试方法后记录它的行为:
this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
这是无能为力的,因为测试方法已经被调用了。
应该以相反的方式完成:
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
this.subject.methodA(name);
此外,模拟对象是第一步。
如果模拟对象没有与被测对象关联,则不会对被测对象产生任何影响。
你应该这样做:
Authent authent = Mockito.mock(Authent.class);
// record behavior for the mock
when(authent.getPassword()).thenReturn("testPW");
// create the object under test with the mock
this.subject = new Subject(authent);
// call your method to test
this.subject.methodA(name);
// do your assertions
...
关于java - Mockito When() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44584554/