Mockito Programming Model: Difference between revisions
Jump to navigation
Jump to search
Line 76: | Line 76: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
The <code>when()</code> configures the method(s) to stub, or the '''trigger action'''. The <code>then*()</code> methods specify what to do when the trigger is activated. The options are: | |||
* <code>thenReturn()</code>: returns the given value. | |||
* <code>thenThrow()</code>: throws the given exception. | |||
* <code>thenAnswer(Answer answer)</code>: execute custom logic and compute a value to return. This turns the [[Software Testing Concepts#Mock|mock]] object into a [[Software Testing Concepts#Fake|fake]]. | |||
==Argument Matcher== | ==Argument Matcher== | ||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> |
Revision as of 16:42, 16 July 2021
Internal
Overview
API
import static org.mockito.Mockito.mock;
import com.example.ExternalDependency;
public class SomeClassTest {
private ExternalDependency mockExternalDependency;
@Before
public void setUp() {
mockExternalDependency = mock(ExternalDependency.class);
}
@Test
public void someTest() throws Exception {
...
}
}
Annotations
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.example.ExternalDependency;
public class SomeClassTest {
private AutoCloseable mocks;
@Mock
private ExternalDependency mockExternalDependency;
@Before
public void openMocks() {
mocks = MockitoAnnotations.openMocks(this);
}
@After
public void releaseMocks() throws Exception {
mocks.close();
}
@Test
public void someTest() throws Exception {
...
}
}
Stub Functionality
A stub returns synthetic responses or throws exceptions when its methods are invoked. Mockito supports stubbing and by returning a given value when a specific method of the managed test double is called. Mockito implements the stub functionality with Mockito.when(<method>).thenReturn(...)
pattern:
public class ExternalDependency {
public String someMethod() {
...
}
}
public class SomeClassTest {
@Mock
private ExternalDependency mockExternalDependency;
@Test
public void someTest() throws Exception {
Mockito.when(mockExternalDependency.someMethod()).thenReturn("some synthetic result");
...
}
}
The when()
configures the method(s) to stub, or the trigger action. The then*()
methods specify what to do when the trigger is activated. The options are:
thenReturn()
: returns the given value.thenThrow()
: throws the given exception.thenAnswer(Answer answer)
: execute custom logic and compute a value to return. This turns the mock object into a fake.
Argument Matcher
public class ExternalDependency {
public String someMethodWithArg(String s) {
...
}
}
import static org.mockito.ArgumentMatchers.isA;
...
Mockito.when(mockExternalDependency.someMethodWithArg(isA(String.class))).thenReturn(...);
}
Why is isA() needed, why not provide the class, directly?