I will write a memorandum of JUnit.
Assert
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
// actual =In case of expect, normal
assertThat(actual, is(expect));
// actual !=In case of expect, normal
assertThat(actual, is(not(expect)));
//error
fail("error reason");
Mockito
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
//When mocking the entire object
Target targetMock = mock(Target.class);
//When mocking only the mock set method
Target targetMock = spy(Target.class);
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
//End normally
doNothing().when(targetMock).targetMethod(anyString(), any(Parameter.class));
//Throw an exception * You can specify an exception or RuntimeException that the target method throws
doThrow(new RuntimeException()).when(targetMock).targetMethod("01");
In the above case, an exception is thrown when the targetMethod method is called with the argument "01". If you want to operate the mock when an arbitrary argument is passed, specify anyString () for String, any (class name) for object, etc.
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
//To the return value"ok"To return
when(targetMock.targetMethod(anyString())).thenReturn("ok");
//For the first and third execution"ok", For the second run"ng"To return
when(targetMock.targetMethod(anyString())).thenReturn("ok", "ng", "ok");
//Throw an exception * You can specify an exception or RuntimeException that the target method throws
when(targetMock.targetMethod(anyString())).thenThrow(new RuntimeException());
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
//Check the number of method executions
//Make sure the targetMethod method was executed only once
verify(targetMock, times(1)).targetMethod(anyString(), anyString());
--Only public methods can be mocked
--Static methods cannot be mocked
-Mock injection by @InjectMocks is abstracted to the direct property of the class specified by @InjectMocks. In other words, it doesn't inject mock for @Inject in @Inject object. If you want to do that, you need to use reflection to push the mock directly into the variable.
Recommended Posts