Java – mockito – I feel like I’m not making full use of its potential
When using mockito, I only use it to simulate dependencies, that is, my workflow looks like the following:
I have a dependent class:
public class C { public C (A a,B b) { this.a = a; this.b = b; } public String fooBar() { return a.foo() + b.bar(); } }
In my test class, I simulated these dependencies and told them what values to return when calling some specified methods:
public class CSpec { private A a = mock(A.class); private B b = mock(B.class); @Test public itShouldReturnFooBar() { when(a.foo()).thenReturn("foo"); when(b.bar()).thenReturn("bar"); C c = new C(a,b); assertThat(c.fooBar().isEqualTo("foobar")); } }
(I hope this example is not too simple or too derivative; -) This works well and allows me to test classes separately (here: C) Nevertheless, I never use mockito's verification method or any other function Is it possible / sufficient to use mockito in this way?
Solution
Validation is usually used to check whether your C actually calls the A. foo () and B. bar () methods So you can add
verify(a).foo(); verify(b).foo();
Before or after an assertion I don't think you need or should use them here, but there are several situations where you need to:
> A or B executes common API invisible / accessible content of C, such as log records > you focus on execution order > you want to make sure you call A.Foo and b.bar only, instead of a.foo2, you can use those simulations as spies, then call A.Foo and then route to aReal.. foo