Reputation: 6747
I know that every method that doesn't do anything shouldn't be tested (or not even exist). The thing is, that my method does something normally, but for the test-scenario I have to mock that thing that it does. But I would still like to assert the parameters that it would send to the external thing.
Sounds more complicated than it is - Check my snippet for better understanding:
class A {
@Inject
private Mailer mailer; // Custom mailer class
public void doSomething() {
Date date = new Date(); // dynamic parameter I do not care about in the test
String parameter = "test"; // The parameter I want to test later
mailer.sendMail(parameter, date);
}
}
class ATest {
@Mock
@Produces
private Mailer mailer;
@Inject
private A classToTest;
@Test
public void testDoSomething() throws Exception {
classToTest.doSomething();
assertThat(??).isEqualTo("test"); //How can I get the value of parameter?
}
}
As you can see I need to mock my emailer, so that I dont send a email everytime a test runs.
It would make no sense to promote parameter
to a global variable.
Is there any way to test the value of parameter
without changing the code of A
? And if not what would be the best solution without messing up my class just for testing?
Upvotes: 1
Views: 271
Reputation: 8311
You need to use Mockito.verify
:
verify(mailer, times(1)).sendMail("test");
Verify checks what happened with your mocks: how many times a method was called, and what arguments were given to that method.
Update:
If you want to exclude certain parameters, you can use org.mockito.Matchers.any
- easier to have it as a static import. (NB: if you do ignore some parameters, then the ones you want to INCLUDE now have to be wrapped in org.mockito.Matchers.eq
).
verify(mailer, times(1)).sendMail(eq("test"), any(Date.class));
Upvotes: 2
Reputation: 144
One way is to parameterize the method doSomething
with a mutable object, that you can set upon method execution and assert in the test method. Otherwise, you may also check for exception thrown for any negative scenario, something like
@Test(expected = EmailSendException.class)
public void testDoSomething(){
....
}
Upvotes: 0