Reputation: 959
I am trying to write unit test which will test fillA
method. I need to verify that doSmth
calling with correctly initialized a
fields.
Here is example.
SecondClass secondClass = new SecondClass();
public void execute() {
A a = new A();
fillA(a);
secondClass.doSmth(a);
}
private void fillA(A a) {
a.setFirstField("first field");
a.setSecondField("second field");
}
class SecondClass {
public void doSmth(A a) {
// doSmth
}
}
class A {
private String firstField;
private String secondField;
// getters and setters
}
Upvotes: 0
Views: 143
Reputation: 29520
To ensure, that secondClass
is invoked, you should use Mockito.verify
.
verify(): to check methods were called with given arguments can use flexible argument matching, for example any expression via the
any()
or capture what arguments where called using@Captor
instead.
For example:
Mockito.verify(secondClass).doSmth(<arg>);
If you want to check that the a
fields are correctly initialized, <arg>
could be:
an instance of A (new A("first field", "second field")
), if A define a proper equals
Arguments passed are compared using equals() method"
a custom A
ArgumentMatcher
ArgumentCaptor
Upvotes: 2
Reputation: 69339
Here's the basic structure of the test you need. You need to mock your SecondClass
instance and inject this into your class under test. I've named your outer class as Bar
.
This code assumes you implement a .equals()
method on the A
class.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BarTest {
@Test
public void testAIsCorrectlyInitialized() throws Exception {
SecondClass secondClass = mock(SecondClass.class);
Bar bar = new Bar();
bar.setSecondClass(secondClass);
A expected = new A();
// here, populate "expected" with correct values
bar.execute();
// Verify call (assumes A implements a proper equals)
verify(secondClass).doSmth(expected);
}
}
Upvotes: 0