2022年10月8日 星期六

[Mockito] Mockito’s Mock Methods

 Source from here


Overview
In this tutorial, we'll illustrate the various uses of the standard static mock methods of the Mockito API.

As in other articles focused on the Mockito framework (like Mockito Verify or Mockito When/Then), the MyList class shown below will be used as the collaborator to be mocked in test cases:
  1. package mockito.prac.p3;  
  2.   
  3. import java.util.AbstractList;  
  4.   
  5. public class MyList extends AbstractList<String>{  
  6.     @Override  
  7.     public String get(int index) {  
  8.         return null;  
  9.     }  
  10.   
  11.     @Override  
  12.     public int size() {  
  13.         return 1;  
  14.     }  
  15. }  
Simple Mocking
The simplest overloaded variant of the mock method is the one with a single parameter for the class to be mocked:
  1. public static <T> T mock(Class<T> classToMock)  
We'll use this method to mock a class and set an expectation:
  1. MyList listMock = Mockito.mock(MyList.class);  
  2. when(listMock.add(anyString())).thenReturn(false);  
Then we'll execute a method on the mock:
  1. boolean added = listMock.add("abc");  
The following code confirms that we invoked the add method on the mock. The invocation returns a value that matches the expectation we set before:
  1. verify(listMock).add(anyString());  
  2. assertEquals(added, false);  
Mocking With Mock's Name
In this section, we'll cover another variant of the mock method, which is provided with an argument specifying the name of the mock:
  1. public static <T> T mock(Class<T> classToMock, String name)  
Generally speaking, the name of a mock has nothing to do with the working code. However, it may be helpful in debugging, as we use the mock's name to track down verification errors. To ensure the exception message thrown from an unsuccessful verification includes the provided name of a mock, we'll use assertThatThrownBy.

In the following code, we'll create a mock for the MyList class and name it myMock:
  1. MyList listMock = Mockito.mock(MyList.class"myMock");  
Then we'll set an expectation on a method of the mock and execute it:
  1. when(listMock.add(anyString())).thenReturn(false);  
  2. listMock.add("abc");  
Next, we'll call the verification inside the assertThrows and verify the instance of the exception thrown:
  1. assertThrows(  
  2.         TooFewActualInvocations.class,  
  3.         () -> verify(listMock, times(2)).add(anyString()));  
Further, we can also verify the exception's message that it should contain the information about the mock:
  1. TooFewActualInvocations exception = assertThrows(  
  2.         TooFewActualInvocations.class,  
  3.         () -> verify(listMock, times(2)).add(anyString()));        
  4. assertTrue(exception.getMessage().contains("myMock.add"));  
Mocking With Answer
Here we'll demonstrate the use of a mock variant in which we'll configure the strategy for the mock's answers to interaction at creation time. This mock method's signature in the Mockito documentation looks like the following:
  1. public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)  
Let's start with the definition of an implementation of the Answer interface:
  1. static class CustomAnswer implements Answer<Boolean> {  
  2.     @Override  
  3.     public Boolean answer(InvocationOnMock invocation) throws Throwable {  
  4.         return false;  
  5.     }  
  6. }  
We'll use the CustomAnswer class above for the generation of a mock:
  1. MyList listMock = Mockito.mock(MyList.classnew CustomAnswer());  
If we don't set an expectation on a method, the default answer, configured by the CustomAnswer type, will come into play. In order to prove this, we'll skip over the expectation setting step and jump to the method execution:
  1. boolean added = listMock.add("abc");  
The following verification and assertion confirm that the mock method with an Answer argument worked as expected:
  1. verify(listMock).add(anyString());  
  2. assertFalse(added);  
Mocking With MockSettings
The final mock method we'll cover in this article is the variant with a parameter of the MockSettings type. We use this overloaded method to provide a non-standard mock.

There are several custom settings supported by methods of the MockSettings interface, such as registering a listener for method invocations on the current mock with invocationListeners, configuring serialization with serializable, specifying the instance to spy on with spiedInstance, configuring Mockito to attempt to use a constructor when instantiating a mock with useConstructor, etc.

For convenience, we'll reuse the CustomAnswer class introduced in the previous section to create a MockSettings implementation that defines a default answer.

MockSettings object is instantiated by a factory method:
  1. MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());  
We'll use that setting object in the creation of a new mock:
  1. MyList listMock = Mockito.mock(MyList.class, customSettings);  
Similar to the preceding section, we'll invoke the add method of a MyList instance, and verify that the mock method with a MockSettings argument works as expected:
  1. boolean added = listMock.add("abc");   
  2.   
  3. verify(listMock).add(anyString());  
  4. assertFalse(added);  


Complete Source Code
The full unit test is as below:
  1. package mockito.prac.p3;  
  2.   
  3. import static org.junit.Assert.assertEquals;  
  4. import static org.junit.Assert.assertFalse;  
  5. import static org.junit.Assert.assertThrows;  
  6. import static org.junit.Assert.assertTrue;  
  7. import static org.mockito.ArgumentMatchers.anyString;  
  8. import static org.mockito.Mockito.times;  
  9. import static org.mockito.Mockito.verify;  
  10. import static org.mockito.Mockito.when;  
  11. import static org.mockito.Mockito.withSettings;  
  12.   
  13. import org.junit.jupiter.api.Test;  
  14. import org.mockito.MockSettings;  
  15. import org.mockito.Mockito;  
  16. import org.mockito.exceptions.verification.TooFewActualInvocations;  
  17. import org.mockito.invocation.InvocationOnMock;  
  18. import org.mockito.stubbing.Answer;  
  19.   
  20. class UsingMockMethod {  
  21.   
  22.     @Test  
  23.     void testSimpleMocking() {  
  24.         MyList listMock = Mockito.mock(MyList.class);  
  25.         when(listMock.add(anyString())).thenReturn(false);  
  26.           
  27.         boolean added = listMock.add("abc");  
  28.           
  29.         verify(listMock).add(anyString());  
  30.         assertEquals(added, false);  
  31.     }  
  32.       
  33.     @Test  
  34.     void testMockingWithMockName() {  
  35.         MyList listMock = Mockito.mock(MyList.class"myMock");  
  36.         when(listMock.add(anyString())).thenReturn(false);  
  37.           
  38.         listMock.add("abc");  
  39.           
  40.         TooFewActualInvocations exception = assertThrows(  
  41.                 TooFewActualInvocations.class,  
  42.                 () -> verify(listMock, times(2)).add(anyString()));        
  43.         assertTrue(exception.getMessage().contains("myMock.add"));  
  44.     }  
  45.       
  46.     static class CustomAnswer implements Answer<Boolean> {  
  47.         @Override  
  48.         public Boolean answer(InvocationOnMock invocation) throws Throwable {  
  49.             return false;  
  50.         }  
  51.     }  
  52.       
  53.     @Test  
  54.     void testMockingWithAnswer() {  
  55.         MyList listMock = Mockito.mock(MyList.classnew CustomAnswer());  
  56.           
  57.         boolean added = listMock.add("abc");   
  58.           
  59.         verify(listMock).add(anyString());  
  60.         assertFalse(added);  
  61.     }  
  62.       
  63.     @Test  
  64.     void testMockingWithMockSettings() {  
  65.         MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());  
  66.         MyList listMock = Mockito.mock(MyList.class, customSettings);  
  67.           
  68.         boolean added = listMock.add("abc");   
  69.           
  70.         verify(listMock).add(anyString());  
  71.         assertFalse(added);  
  72.     }  
  73. }  

This message was edited 17 times. Last update was at 09/10/2022 14:24:01

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...