Mockito Programming Model: Difference between revisions
Jump to navigation
Jump to search
Line 55: | Line 55: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Stub Functionality= | =Stub Functionality= | ||
A [[Software_Testing_Concepts#Stub|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 <code>Mockito.when(<method>).thenReturn(...)</code> pattern: | A [[Software_Testing_Concepts#Stub|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 [[Mockito_Concepts#Managed_Test_Double|managed test double]] is called. Mockito implements the stub functionality with <code>Mockito.when(<method>).thenReturn(...)</code> pattern: | ||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> | ||
public class SomeClassTest { | public class SomeClassTest { |
Revision as of 04:28, 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 SomeClassTest {
@Mock
private ExternalDependency mockExternalDependency;
@Test
public void someTest() throws Exception {
Mockito.when(mockExternalDependency.someMethod()).thenReturn("some synthetic result");
...
}
}