Reputation: 157
So I break down my code a bit to make it more general and also easier for others to understand with the similar issue
this is my main code:
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 {}");
}
}
}
}
while my test code looks like this:
@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());
}
as I said the code is more complex I broke it down and made it shorter..... hope still it is readable.
My problem is not that my when().thenReturn()
doesn't work and therefore my code doesn't proceed further.... I guess my mocking doesn't work properly for some reason.
Upvotes: 0
Views: 12328
Reputation: 26492
You have to mock before you invoke the method under test. Also you have to inject that mock into your class under test.
With added structural comments this would look like:
@Test
public void testMethodA() throws Exception {
// Arrange
final String name = "testName";
Authent authentMock = Mockito.mock(Authent.class);
when(authentMock.getPassword()).thenReturn("testPW");
this.subject.setAuthent(authentMock);
// Act
this.subject.methodA(name);
// Assert
assertEquals(1, logger.infos.size());
}
Upvotes: 1
Reputation: 131326
You test the methodA()
method but you mock the Authent
class and record a behavior for it after invoking the tested method :
this.subject.methodA(name);
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
This is helpless as the method to test was already invoked.
It should be done in the reverse way :
Authent authent = Mockito.mock(Authent.class);
when(authent.getPassword()).thenReturn("testPW");
this.subject.methodA(name);
Besides, mocking an object is first step.
If the mocked object is not associated to the object under test, it will have no effect on the object under test.
You should do something in this way :
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
...
Upvotes: 6