I'm using Mock for unit tests, so I'd like to summarize it easily as a review.
Simply put ** "Called from the class under test, A substitute for parts (other sources). "
For example, a test target class that outputs calculation results, Suppose you have a subclass that actually does the calculations for you.
Mock takes the place of this subclass. That is.
Sub sub = Mock(Sub.class);
Create a mock object using the Mock method
2.Mockito.when().thenReturn();
//a is the part call processing
//b is the value returned by the called part
Mockoito.when(sub.getAns()).thenReturn(b);
I'm calling the Sub class in the source under test, When passing the test, if the part called Sub is not completed The test fails at the call part and I can't pass it to the end. Therefore, when the getAns method of Sub class is called using the above process, If you instruct it to return the value b, you can pass the process in the test.
3.MockObjectManager.setReturnValueAt
//1st argument=Class designation
//2nd argument=Method name
//3rd argument=Number of calls
//4th argument=Return value setting
MockObjectManager.setReturnValueAt(Sub.class, "getAns", 0, b);
MockObjectManager.setReturnValueAt(Sub.class, "getAns", 1, b);
Also used with Mockito.when in 2. Note the number of calls to the third argument. If the same part is used multiple times in the source under test, It is necessary to write according to the number of times.
4.Mockito.any
//Mockito.any example
//↓ A setting that returns b no matter what int type comes
Mockito.when(sub.getAns(Mocito.anyInt(), Mockito.anyInt())).thenReturn(b);
In the Main class to be tested, without specifying the argument when calling sub.getAns If it is an int type, it is good.
This is mainly used when you want to see the coverage mainly. There are also Mockito.anyString (), Mockito.anyMap (), and cast (class) Mockito.any.
//Main=Source to be tested
Main main = new Main();
//Sub=Other class parts
Sub sub = new Sub();
//↓ ↓ Other things I was using
//Specify the variable sub declared in the field of Main class
Field field = Main.getDeclaredField("sub");
//Remove restrictions on access to private variables
field.setAccessible(true);
//Set a value for a private variable
field.set(main, sub);
If you use it in a series of steps for Mocking, it will be as follows.
Sub sub = Mock(Sub.class);
Field field = main.getDeclaredField("sub");
field.setAccessible(true);
field.set(main, sub);
//If getAns is a method of adding two arguments
Mockito.when(sub.getAns(1,1)).thenReturn(2);
Sub sub = Mock(Sub.class);
Field field = main.getDeclaredField("sub");
field.setAccessible(true);
field.set(main, sub);
//When the formal argument of getAns is DTO type
AnsDTO ansDto = new AnsDTO();
ansDto.setMath1(1);
ansDto.setMath2(1);
Mockito.when(sub.getAns(ansDto)).thenReturn(3);
Recommended Posts