{"id":6664,"date":"2022-07-26T17:25:05","date_gmt":"2022-07-26T09:25:05","guid":{"rendered":"http:\/\/123.57.164.21\/?p=6664"},"modified":"2022-07-26T17:42:04","modified_gmt":"2022-07-26T09:42:04","slug":"mockito%e7%9a%84%e4%bd%bf%e7%94%a8%e5%8f%8a%e5%8e%9f%e7%90%86%e6%b5%85%e6%9e%90","status":"publish","type":"post","link":"https:\/\/92it.top\/?p=6664","title":{"rendered":"Mockito\u7684\u4f7f\u7528\u53ca\u539f\u7406\u6d45\u6790(\u63a8\u8350)"},"content":{"rendered":"\n<p>\u5728\u5fae\u670d\u52a1\u6a2a\u884c\u7684\u5e74\u4ee3\uff0c\u4e00\u4e2a\u670d\u52a1\u53ef\u80fd\u4f9d\u8d56\u4e86\u82e5\u5e72\u4e2a\u5176\u5b83\u670d\u52a1\uff0c\u800c\u8fd9\u4e9b\u88ab\u4f9d\u8d56\u7684\u670d\u52a1\uff0c\u53c8\u6781\u53ef\u80fd\u4f9d\u8d56\u4e86\u522b\u7684\u670d\u52a1\uff0c\u4e8e\u662f\u6784\u6210\u4e86\u4e00\u4e2a\u590d\u6742\u7684\u4f9d\u8d56\u94fe\u3002\u800c\u65e5\u5e38\u5f00\u53d1\u4e2d\uff0c\u7ecf\u5e38\u4f1a\u82e6\u607c\u4e8e\u67d0\u67d0\u4e0a\u6e38\u63a5\u53e3\u6ca1\u6570\u636e\u800c\u6240\u4f7f\u5f97UT\u8fbe\u4e0d\u5230\u9884\u671f\u7684\u76ee\u6807\uff0c\u6240\u5174\u73b0\u5728\u5df2\u7ecf\u6709\u4e86\u591a\u79cdMock Toolkit\uff0c\u5f88\u597d\u7684\u89e3\u51b3\u4e86\u8fd9\u4e00\u75db\u70b9\u3002\u6bd4\u8f83\u5e38\u7528\u7684\u6709EasyMock,JMockit,Mockito,PowerMock\u7b49\uff0c\u800c\u672c\u6587\u4e3b\u8981\u4ecb\u7ecdMockito\u7684\u7b80\u5355\u4f7f\u7528\uff0c\u5e76\u5bf9\u5176\u5b9e\u73b0\u539f\u7406\u8fdb\u884c\u7b80\u5355\u5206\u6790\u3002<\/p>\n\n\n\n<p><strong>Mockito\u7684\u4f7f\u7528<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p>\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u4f1a\u5728UT\u91cc\u4f7f\u7528@Mock\u3001@Spy\u4ee5\u53ca@InjectMocks\u7b49\u6ce8\u89e3\u6765Mock\u6389\u4e00\u4e9b\u4e0d\u53ef\u63a7\u7684\u4e0a\u4e0b\u6e38\u63a5\u53e3\uff0c\u4e3a\u4e86\u7b80\u5316\u8bf4\u660e\uff0c\u6211\u4eec\u5c06\u4f8b\u5b50\u7b80\u5355\u5316\u3002<br>\u5047\u8bbe\u6709\u8fd9\u6837\u7684\u4e00\u4e2a\u670d\u52a1<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class ServiceA {\n\n    @Autowired\n    private ServiceB serviceB;\n    \n    public String hello(String name) {\n        return \"ServiceA.hello:\" + name;\n    }\n    \n    public String helloB(String name) {\n        return serviceB.hello(name);\n    }\n}\n<\/pre>\n\n\n\n<p><strong>@Mock<\/strong><\/p>\n\n\n\n<p>\u73b0\u5728\u6211\u4eec\u6765\u5c06\u5b83mock\u6389<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class MockTest {\n    \n    @Mock\n    private ServiceA seriveA;\n\n    @Before\n    public void init() {\n        MockitoAnnotations.initMocks(this);\n    }\n    \n    @Test\n    public void testA() {\n        Mockito.when(seriveA.hello(\"aaa\")).thenReturn(\"111\").thenReturn(\"222\");  \/\/\u6253\u6869\n        System.out.println(seriveA.hello(\"aaa\"));   \/\/111                        \/\/\u771f\u5b9e\u8c03\u7528\n        System.out.println(seriveA.hello(\"aaa\"));   \/\/222\n        System.out.println(seriveA.hello(\"bbb\"));   \/\/null\n    }\n}\n<\/pre>\n\n\n\n<p>\u4e3a\u4e86\u4fbf\u4e8e\u63cf\u8ff0\uff0c\u5148\u7b80\u5355\u8bf4\u660e\u4e00\u4e0b\uff1a\u4e0a\u9762serviceA.hello(\u201caaa\u201d)\u8c03\u7528\u7ed3\u679c\u505a\u4e3a\u5165\u53c2\u4f20\u9012\u7ed9when()\u65b9\u6cd5\uff0c\u6211\u4eec\u79f0\u4e3a\u6253\u6869\uff0c\u800c\u540e\u9762\u7684\u8c03\u7528\u662f\u6211\u4eec\u79f0\u4e3a\u771f\u5b9e\u8c03\u7528\u3002<br>Mockito\u63d0\u4f9b\u4e86\u901a\u4fd7\u6613\u7528\u7684API\uff0c@Mock\u6ce8\u91ca\u7528\u4e8e\u5bf9\u76ee\u6807\u5bf9\u8c61\u8fdb\u884cmock\uff0c\u751f\u6210\u7acbmock\u5bf9\u8c61\uff0cwhen\u2026thenReturn\u2026\u7528\u4e8e\u6a21\u62df\u8fd4\u56de\u7ed3\u679c\uff0c\u5f53\u8c03\u7528\u67d0\u67d0\u65b9\u6cd5\u65f6\u8fd4\u56de\u6211\u4eec\u60f3\u8981\u7684\u9884\u5b9a\u7ed3\u679c\uff0c thenThrow\u5219\u7528\u4e8e\u6a21\u62df\u76ee\u6807\u65b9\u6cd5\u629b\u51fa\u5f02\u5e38\uff0c\u800c\u6211\u4eec\u4e5f\u53ef\u4ee5\u4f7f\u7528\u65b9\u6cd5\u94fe\u6a21\u62df\u8fd4\u56de\u591a\u4e2amock\u7ed3\u679c\uff0c\u5728\u591a\u6b21\u8c03\u7528\u76ee\u6807\u65b9\u6cd5\u65f6\uff0cMockito\u4f1a\u4f9d\u6b21\u4e3a\u6211\u4eec\u8fd4\u56de\u9884\u5148\u8bbe\u5b9a\u7684mock\u7ed3\u679c\u3002<\/p>\n\n\n\n<p><strong>@InjectMocks<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p>ServiceA\u4f9d\u8d56\u4e86ServiceB\uff0c\u5982\u679c\u6211\u4eec\u8981mock\u7684\u4e0d\u662fServiceA\uff0c\u800c\u662fServiceB\uff0c\u90a3\u6211\u4eec\u53ef\u4ee5\u5728UT\u91cc\uff0c\u7ed9ServiceB\u52a0\u6ce8\u91ca@Mock\uff0c\u7ed9ServiceA\u52a0\u4e0a\u6ce8\u91ca@InjectMocks\uff0c\u8fd9\u65f6Mockito\u4f1a\u81ea\u52a8\u4e3aServiceA\u6ce8\u5165mock\u5bf9\u8c61ServiceB<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class MockTest2 {\n    \n    @InjectMocks\n    private ServiceA serviceA;\n    @Mock\n    private ServiceB serviceB;\n    \n    @Before\n    public void init() {\n        MockitoAnnotations.initMocks(this);\n    }\n    \n    @Test\n    public void testB() {\n        Mockito.when(serviceB.hello(\"aaa\")).thenReturn(\"111\").thenReturn(\"222\");\n        System.out.println(serviceA.helloB(\"aaa\"));   \/\/111\n        System.out.println(serviceA.helloB(\"aaa\"));   \/\/222\n        System.out.println(serviceA.helloB(\"bbb\"));   \/\/null\n    }\n}\n<\/pre>\n\n\n\n<p>\u4ece\u4e0a\u9762\u7684\u7528\u6cd5\u4e2d\uff0c\u6574\u4e2amock\u7684\u8fc7\u7a0b\u5927\u6982\u53ef\u4ee5\u5206\u4e3a\u4e09\u6b65\uff1a<\/p>\n\n\n\n<ul><li>1\uff09@Mock\u6ce8\u89e3\u58f0\u660e\u4e86\u8981\u5c06\u5bf9\u8c61\u8fdb\u884cmock\u3002<\/li><li>2\uff09\u4f7f\u7528MockitoAnnotations.initMocks\u544a\u8bc9Mockito\u8981\u5bf9\u5f53\u524d\u5bf9\u8c61\u8fdb\u884cmock\u5904\u7406\u3002\u5f53\u7136\u4f60\u7528\u53ef\u4ee5\u4f7f\u7528@RunWith(MockitoJUnitRunner.class)\uff0c\u6b8a\u9014\u540c\u5f52\u3002<\/li><li>3\uff09\u4f7f\u7528when\u2026thenReturn\u6765\u6a21\u62df\u8fd4\u56de\u3002<\/li><\/ul>\n\n\n\n<p>\u63a5\u4e0b\u6765\u6211\u4eec\u6765\u5206\u6790\u4e00\u4e0b\u5176\u5b9e\u73b0\u539f\u7406\u3002<\/p>\n\n\n\n<p><strong>Mockito\u7684\u5b9e\u73b0\u539f\u7406<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><strong>mock\u5bf9\u8c61\u7684\u521b\u5efa<\/strong><\/p>\n\n\n\n<p>\u9996\u5148\u6211\u4eec\u770b\u770bMockitoAnnotations.initMocks\u5230\u5e95\u505a\u4e86\u4ec0\u4e48\uff1f\u4e00\u8d77\u8fdb\u5165\u6e90\u7801\u3002<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static void initMocks(Object testClass) {\n        if (testClass == null) {\n            throw new MockitoException(\"testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class\");\n        }\n\n        AnnotationEngine annotationEngine = new GlobalConfiguration().getAnnotationEngine();\n        Class&lt;?> clazz = testClass.getClass();\n\n        \/\/below can be removed later, when we get read rid of deprecated stuff\n        if (annotationEngine.getClass() != new DefaultMockitoConfiguration().getAnnotationEngine().getClass()) {\n            \/\/this means user has his own annotation engine and we have to respect that.\n            \/\/we will do annotation processing the old way so that we are backwards compatible\n            while (clazz != Object.class) {\n                scanDeprecatedWay(annotationEngine, testClass, clazz);\n                clazz = clazz.getSuperclass();\n            }\n        }\n\n        \/\/anyway act 'the new' way\n        annotationEngine.process(testClass.getClass(), testClass);\n    }\n<\/pre>\n\n\n\n<p>\u8fd9\u91cc\u6709\u4e2aAnnotationEngine\uff0c\u4ece\u540d\u79f0\u4e2d\u6211\u4eec\u5927\u6982\u53ef\u4ee5\u731c\u5230Mockito\u662f\u8981\u5bf9Annotation\u6bd4\u5982\uff1a@Mock,@Spy,@InjectMocks\u7b49\u8fdb\u884c\u5904\u7406\uff0c\u4ee5\u6b64\u521b\u5efa\u51faMock\u5bf9\u8c61\u3002<br>AnnotationEngine\u6709\u4e09\u4e2a\u5b9e\u73b0\uff0cDefaultAnnotationEngine,SpyAnnotationEngine,InjectingAnnotationEngine,\u8fd9\u4e09\u4e2aAnnotationEngine\u5408\u5206\u522b\u5904\u7406@Mock\u3001@Spy\u548cInjectMocks\u6ce8\u89e3\u3002\u8fd9\u91cc\u9009\u62e9DefaultAnnotationEngine\u8fdb\u884c\u5206\u6790\u3002<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public void process(Class&lt;?> clazz, Object testInstance) {\n        Field[] fields = clazz.getDeclaredFields();\n        for (Field field : fields) {\n            boolean alreadyAssigned = false;\n            for(Annotation annotation : field.getAnnotations()) {           \n                Object mock = createMockFor(annotation, field);\n                if (mock != null) {\n                    throwIfAlreadyAssigned(field, alreadyAssigned);                    \n                    alreadyAssigned = true;                    \n                    try {\n                        new FieldSetter(testInstance, field).set(mock);\n                    } catch (Exception e) {\n                        throw new MockitoException(\"Problems setting field \" + field.getName() + \" annotated with \"\n                                + annotation, e);\n                    }\n                }        \n            }\n        }\n    }\n<\/pre>\n\n\n\n<p>\u5728\u8fd9\u91cc\u770b\u5230createMockFor\uff0c\u7531\u4e8e\u4ee3\u7801\u8fd8\u6bd4\u8f83\u957f\uff0c\u7565\u53bb\u4ee3\u7801\uff0c\u76f4\u63a5\u770b\u4e0b\u9762\u7684\u6d41\u7a0b\u56fe<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/123.57.164.21\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-1024x319.png\" alt=\"\" class=\"wp-image-6667\" width=\"615\" height=\"191\" srcset=\"https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-1024x319.png 1024w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-300x94.png 300w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-768x239.png 768w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-1536x479.png 1536w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-830x259.png 830w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-230x72.png 230w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-350x109.png 350w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249-480x150.png 480w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-249.png 1758w\" sizes=\"(max-width: 615px) 100vw, 615px\" \/><\/figure><\/div>\n\n\n\n<p>\u4ece\u6d41\u7a0b\u662f\u6211\u4eec\u5927\u6982\u77e5\u9053\uff0cMockitoAnnotations.initMocks(this)\u7684\u8fc7\u7a0b\u5c31\u662f\u521b\u5efamock\u5bf9\u8c61\u7684\u8fc7\u7a0b\uff0cMockito\u57281.x\u7248\u672c\u4e2d\u662f\u91c7\u7528cglib\u52a8\u6001\u521b\u5efa\u88abmock\u7684\u76ee\u6807\u7c7b\u7684\u4ee3\u7406\u7c7b(2.x\u7248\u672c\u6539\u7528\u4e86bytebuddy)\uff0c\u4ee3\u7406\u7c7b\u662f\u88abmock\u76ee\u6807\u7c7b\u7684\u5b50\u7c7b\uff0c\u56e0\u6b64Mocktio\u65e0\u6cd5mock\u88ab\u5b9a\u4e49\u4e3afinal\u7684\u7c7b\u548c\u65b9\u6cd5\uff08<strong>\u57283.4\u7248\u672c\u4ee5\u540e\uff0cMockito\u53ef\u4ee5Mock final\u7684\u7c7b\u548c\u65b9\u6cd5<\/strong>\uff09\u3002\u800c\u5728\u521b\u5efa\u76ee\u6807mock\u5bf9\u8c61\u65f6\uff0cMocktio\u5229\u7528cglib\u7ed9mock\u5bf9\u8c61\u52a0\u4e0a\u4e86\u65b9\u6cd5\u62e6\u622a\u5668(MethodInterceptorFilter)\uff0c\u8fd9\u6837\u5f53mock\u5bf9\u8c61\u7684\u65b9\u6cd5\u88ab\u8c03\u7528\u65f6\uff0c\u4f1a\u88ab\u62e6\u622a\u5668\u8fdb\u884c\u62e6\u622a\u5904\u7406\u3002\u5176\u4e2d\u5173\u952e\u7684\u4ee3\u7406\u7c7b\u7684\u751f\u6210\u548c\u5bf9\u8c61\u5b9e\u4f8b\u662f\u521b\u5efa\u662f\u5728ClassImposterizer\u4e2d\u5b8c\u6210\u7684\uff0c\u4ee3\u7801\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public Class&lt;Factory> createProxyClass(Class&lt;?> mockedType, Class&lt;?>... interfaces) {\n        if (mockedType == Object.class) {\n            mockedType = ClassWithSuperclassToWorkAroundCglibBug.class;\n        }\n        \n        Enhancer enhancer = new Enhancer() {\n            @Override\n            @SuppressWarnings(\"unchecked\")\n            protected void filterConstructors(Class sc, List constructors) {\n                \/\/ Don't filter\n            }\n        };\n        Class&lt;?>[] allMockedTypes = prepend(mockedType, interfaces);\n\t\tenhancer.setClassLoader(SearchingClassLoader.combineLoadersOf(allMockedTypes));\n        enhancer.setUseFactory(true);\n        if (mockedType.isInterface()) {\n            enhancer.setSuperclass(Object.class);\n            enhancer.setInterfaces(allMockedTypes);\n        } else {\n            enhancer.setSuperclass(mockedType);\n            enhancer.setInterfaces(interfaces);\n        }\n        enhancer.setCallbackTypes(new Class[]{MethodInterceptor.class, NoOp.class});\n        enhancer.setCallbackFilter(IGNORE_BRIDGE_METHODS);\n        if (mockedType.getSigners() != null) {\n            enhancer.setNamingPolicy(NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES);\n        } else {\n            enhancer.setNamingPolicy(MockitoNamingPolicy.INSTANCE);\n        }\n\n        enhancer.setSerialVersionUID(42L);\n        \n        try {\n            return enhancer.createClass(); \n        } catch (CodeGenerationException e) {\n            if (Modifier.isPrivate(mockedType.getModifiers())) {\n                throw new MockitoException(\"\\n\"\n                        + \"Mockito cannot mock this class: \" + mockedType \n                        + \".\\n\"\n                        + \"Most likely it is a private class that is not visible by Mockito\");\n            }\n            throw new MockitoException(\"\\n\"\n                    + \"Mockito cannot mock this class: \" + mockedType \n                    + \"\\n\" \n                    + \"Mockito can only mock visible &amp; non-final classes.\"\n                    + \"\\n\" \n                    + \"If you're not sure why you're getting this error, please report to the mailing list.\", e);\n        }\n    }\n    \n    private Object createProxy(Class&lt;Factory> proxyClass, final MethodInterceptor interceptor) {\n        Factory proxy;\n        try {\n            proxy = instantiator.newInstance(proxyClass);\n        } catch (InstantationException e) {\n            throw new MockitoException(\"Unable to create mock instance of type '\" + proxyClass.getSuperclass().getSimpleName() + \"'\", e);\n        }\n        proxy.setCallbacks(new Callback[] {interceptor, SerializableNoOp.SERIALIZABLE_INSTANCE });\n        return proxy;\n<\/pre>\n\n\n\n<p><strong>when().thenReturn()<\/strong><\/p>\n\n\n\n<p>\u5206\u6790\u5b8cmock\u5bf9\u8c61\u7684\u6784\u5efa\uff0c\u63a5\u4e0b\u6765\u8bf4when()\u2026thenReturn()\u2026\uff0c\u5176\u4e2dwhen()\u65b9\u6cd5\u5165\u53c2\u662fObject\u5bf9\u8c61\uff0c\u6211\u4eec\u4e00\u822c\u662f\u5148\u8c03\u7528\u76ee\u6807\u65b9\u6cd5\u7136\u540e\u5c06\u5176\u8fd4\u56de\u503c\u4f20\u7ed9when()\uff08\u8be5\u6b65\u9aa4\u4e5f\u88ab\u79f0\u4e3a\u6253\u6869\uff09\uff0c\u800c\u5bf9\u76ee\u6807\u65b9\u6cd5\u7684\u8c03\u7528\u4f1a\u5148\u88ab\u62e6\u622a\u5668(MethodInterceptorFilter)\u62e6\u622a\uff0c\u6700\u540e\u7531MockHandlerImpl\u8fdb\u884c\u5904\u7406\uff0c\u4ee3\u7801\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public Object handle(Invocation invocation) throws Throwable {\n\t\tif (invocationContainerImpl.hasAnswersForStubbing()) {\n            \/\/ stubbing voids with stubVoid() or doAnswer() style\n            InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(\n                    mockingProgress.getArgumentMatcherStorage(),\n                    invocation\n            );\n            invocationContainerImpl.setMethodForStubbing(invocationMatcher);\n            return null;\n        }\n        VerificationMode verificationMode = mockingProgress.pullVerificationMode();\n\n        InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(\n                mockingProgress.getArgumentMatcherStorage(),\n                invocation\n        );\n\n        mockingProgress.validateState();\n\n        \/\/ if verificationMode is not null then someone is doing verify()\n        if (verificationMode != null) {\n            \/\/ We need to check if verification was started on the correct mock\n            \/\/ - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)\n            if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {\n                VerificationDataImpl data = createVerificationData(invocationContainerImpl, invocationMatcher);\n                verificationMode.verify(data);\n                return null;\n            } else {\n                \/\/ this means there is an invocation on a different mock. Re-adding verification mode\n                \/\/ - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)\n                mockingProgress.verificationStarted(verificationMode);\n            }\n        }\n\n        \/\/ prepare invocation for stubbing\n        invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);\n        OngoingStubbingImpl&lt;T> ongoingStubbing = new OngoingStubbingImpl&lt;T>(invocationContainerImpl);\n        mockingProgress.reportOngoingStubbing(ongoingStubbing);\n\n        \/\/ look for existing answer for this invocation\n        StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);\n\n        if (stubbedInvocation != null) {\n            stubbedInvocation.captureArgumentsFrom(invocation);\n            return stubbedInvocation.answer(invocation);\n        } else {\n             Object ret = mockSettings.getDefaultAnswer().answer(invocation);\n\n            \/\/ redo setting invocation for potential stubbing in case of partial\n            \/\/ mocks \/ spies.\n            \/\/ Without it, the real method inside 'when' might have delegated\n            \/\/ to other self method and overwrite the intended stubbed method\n            \/\/ with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.\n            invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);\n            return ret;\n        }\n}\n<\/pre>\n\n\n\n<p>\u4e3b\u8981\u903b\u8f91\u662f\u5224\u65ad\u5f53\u524d\u7684\u8c03\u7528\u662f\u6253\u6869\u8fd8\u662f\u771f\u5b9e\u8c03\u7528\uff0c\u5982\u679c\u662f\u6253\u6869\uff0c\u5219\u5c06\u5f53\u524d\u8c03\u7528\u4fe1\u606f(Invocation)\u4ea4\u7ed9InvocationContainerImpl\u8fdb\u884c\u8bb0\u5f55\uff0c\u5982\u679c\u4e0d\u662f\uff0c\u5219\u4eceInvocationContainerImpl\u4e2d\u67e5\u627eStubbedInvocationMatcher\uff0c\u800cStubbedInvocationMatcher\u7ef4\u62a4\u7740\u4e00\u4e2a\u7531mock\u65b9\u6cd5\u7684mock\u7ed3\u679c\u7ec4\u6210\u7684\u961f\u5217\uff0c\u53ef\u4ee5\u6839\u636e\u5ba2\u6237\u7aef\u7684\u8c03\u7528\u4f9d\u6b21\u8fd4\u56demock\u7ed3\u679c\u3002<br>thenReturn()\u662fOngoingStubbing\u63a5\u53e3\u5b9a\u4e49\u7684\u65b9\u6cd5\uff0c\u7531BaseStubbing\u62bd\u8c61\u7c7b\u5b9e\u73b0\uff0c\u5e76\u6700\u7ec8\u4f1a\u8c03\u7528OngoingStubbingImpl\u7684thenAnswer(),\u6700\u540e\u5c06mock\u4ea4\u7ed9InvocationContainerImpl\u8fdb\u884c\u8bb0\u5f55\u3002OngoingStubbingImpl\u90e8\u5206\u6e90\u7801\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public OngoingStubbing&lt;T> thenAnswer(Answer&lt;?> answer) {\n        if(!invocationContainerImpl.hasInvocationForPotentialStubbing()) {\n            new Reporter().incorrectUseOfApi();\n        }\n\n        invocationContainerImpl.addAnswer(answer);\n        return new ConsecutiveStubbing&lt;T>(invocationContainerImpl);\n    }\n<\/pre>\n\n\n\n<p>\u6574\u4e2awhen().thenReturn()\u7684\u8fc7\u7a0b\u5982\u4e0b\uff1a<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/123.57.164.21\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-1024x322.png\" alt=\"\" class=\"wp-image-6669\" width=\"652\" height=\"205\" srcset=\"https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-1024x322.png 1024w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-300x94.png 300w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-768x241.png 768w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-1536x483.png 1536w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-830x261.png 830w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-230x72.png 230w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-350x110.png 350w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250-480x151.png 480w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-250.png 1902w\" sizes=\"(max-width: 652px) 100vw, 652px\" \/><\/figure><\/div>\n\n\n\n<p><br><\/p>\n\n\n\n<p>\u6267\u884c\u5b8cwhen()\u2026thenReturn\u2026\uff0c\u5219\u5b8c\u6210\u4e86\u6253\u6869\uff0c\u63a5\u4e0b\u6765\u8c03\u7528\u76ee\u6807\u65b9\u6cd5\uff0cMockHandlerImpl\u4eceInvoncationContainerImpl\u67e5\u8be2\u5230mock\u7ed3\u679c\uff0c\u76f4\u63a5\u8fd4\u56de\u7ed9\u5ba2\u6237\u7aef(TestCase)\u3002<br>\u4e86\u89e3\u5b8c\u6574\u4e2amock\u7684\u5b9e\u73b0\u8fc7\u7a0b\uff0c\u53ef\u4ee5\u81ea\u5df1\u5b9e\u73b0\u4e00\u4e2a\u7b80\u5355\u7684mock\u5de5\u5177\u3002<\/p>\n\n\n\n<p><strong>mock\u5de5\u5177\u7684\u7b80\u6613\u5b9e\u73b0<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p>\u5148\u6765\u4e2a\u603b\u89c8<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/123.57.164.21\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-1024x857.png\" alt=\"\" class=\"wp-image-6671\" width=\"434\" height=\"363\" srcset=\"https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-1024x857.png 1024w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-300x251.png 300w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-768x643.png 768w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-830x695.png 830w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-230x192.png 230w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-350x293.png 350w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251-480x402.png 480w, https:\/\/92it.top\/wp-content\/uploads\/2022\/07\/\u56fe\u7247-251.png 1066w\" sizes=\"(max-width: 434px) 100vw, 434px\" \/><\/figure><\/div>\n\n\n\n<p>MockTool\uff1a\u4e3b\u5165\u53e3<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class MockTool {\n\n    private static final MockMethodInterceptor INTERCEPTOR = new MockMethodInterceptor();\n    \n    public static &lt;T> T mock(Class&lt;T> type) {\n        Enhancer enhancer = new Enhancer();\n        enhancer.setSuperclass(type);\n        enhancer.setCallbackFilter((method)->method.isBridge() ? 1 : 0);\/\/\u5ffd\u7565bridge\u65b9\u6cd5\n        enhancer.setCallbacks(new Callback[] {INTERCEPTOR, NoOp.INSTANCE});\n        return type.cast(enhancer.create());\n    }\n\t\n\tpublic static &lt;T> Stubbing when(T call) {\n\t\treturn new Stubbing();\n\t}\n}\n<\/pre>\n\n\n\n<p>MockMethodInterceptor\uff1a\u62e6\u622a\u76ee\u6807\u65b9\u6cd5\uff0c\u8bb0\u5f55\u5e76\u8fd4\u56demock\u7ed3\u679c<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class MockMethodInterceptor implements MethodInterceptor {\n\n    @Override\n    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {\n        Invocation invocation = new Invocation(obj.getClass(), method, args);\n        Object value = InvocationContainer.findAnswerFor(invocation);\n        if (value == null) {\n            \/\/\u67e5\u8be2\u4e0d\u5230mock\u7ed3\u679c,\u89c6\u4e3a\u8981\u6253\u6869\n            InvocationContainer.setCurrentInvocation(invocation);\n        }\n        return value;\n    }\n    \n}<\/pre>\n\n\n\n<p>InvocationContainer\uff1a\u8bb0\u5f55\u5f53\u524d\u8981mock\u7684\u65b9\u6cd5\uff0c\u4ee5\u53camock\u7ed3\u679c<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class InvocationContainer {\n\n    private static Invocation currentInvocation;\n\n    private static final ConcurrentHashMap&lt;Invocation, Queue&lt;Object>> INVOCATION_RETURN_MAP = new ConcurrentHashMap&lt;>();\n\n    public static void setCurrentInvocation(Invocation invocation) {\n        InvocationContainer.currentInvocation = invocation;\n    }\n\n    public static Invocation getCurrentInvocation() {\n        return currentInvocation;\n    }\n\n    public static void addAnswer(Invocation invocation, Object value) {\n        Queue&lt;Object> queue = INVOCATION_RETURN_MAP.get(invocation);\n        if (queue == null) {\n            queue = new ConcurrentLinkedQueue&lt;>();\n            INVOCATION_RETURN_MAP.put(invocation, queue);\n        }\n        queue.offer(value);\n    }\n\n    public static Object findAnswerFor(Invocation invocation) {\n        Queue&lt;Object> queue = INVOCATION_RETURN_MAP.get(invocation);\n        if (queue == null) {\n            return queue;\n        }\n        return queue.size() > 1 ? queue.poll() : queue.peek();\n    }\n<\/pre>\n\n\n\n<p>Invocation\uff1a\u62bd\u8c61\u5bf9\u65b9\u6cd5\u7684\u8c03\u7528<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Setter\n@Getter\n@AllArgsConstructor\n@EqualsAndHashCode\npublic class Invocation {\n    \n    private Class&lt;?> mockClass;\n    private Method method;\n    private Object[] args;\n    \n}\n<\/pre>\n\n\n\n<p>Stubbing\uff1a\u5c06mock\u7ed3\u679c\u5199\u5165mock\u7ed3\u679c\u5bb9\u5668<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class Stubbing {\n\n    public Stubbing thenReturn(Object result) {\n        if (InvocationContainer.getCurrentInvocation() != null) {\n            InvocationContainer.addAnswer(InvocationContainer.getCurrentInvocation(), result);\n        } else {\n            throw new IllegalStateException(\"api\u4f7f\u7528\u59ff\u52bf\u4e0d\u5bf9\");\n        }\n        return this;\n    }\n}\n<\/pre>\n\n\n\n<p>\u6700\u540e\u8d70\u4e00\u4e2a\u6d4b\u8bd5\uff0c\u57fa\u672c\u8fbe\u6807\u3002<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class TestMockTool {\n\n    @Test\n    public void testMock() {\n        ServiceA serviceA = MockTool.mock(ServiceA.class);\n        MockTool.when(serviceA.hello(\"aaa\")).thenReturn(\"111\").thenReturn(\"222\");\n        System.out.println(serviceA.hello(\"aaa\")); \/\/111\n        System.out.println(serviceA.hello(\"aaa\")); \/\/222\n        System.out.println(serviceA.hello(\"bbb\")); \/\/null\n    }\n}\n<\/pre>\n\n\n\n<p>\u8f6c\u8f7d\uff1ahttps:\/\/blog.csdn.net\/vipshop_fin_dev\/article\/details\/106975219<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5728\u5fae\u670d\u52a1\u6a2a\u884c\u7684\u5e74\u4ee3\uff0c\u4e00\u4e2a\u670d\u52a1\u53ef\u80fd\u4f9d\u8d56\u4e86\u82e5\u5e72\u4e2a\u5176\u5b83\u670d\u52a1\uff0c\u800c\u8fd9\u4e9b\u88ab\u4f9d\u8d56\u7684\u670d\u52a1\uff0c\u53c8\u6781\u53ef\u80fd\u4f9d\u8d56\u4e86\u522b\u7684\u670d\u52a1\uff0c\u4e8e\u662f\u6784\u6210\u4e86\u4e00 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[26],"tags":[],"_links":{"self":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/6664"}],"collection":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=6664"}],"version-history":[{"count":8,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/6664\/revisions"}],"predecessor-version":[{"id":6675,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/6664\/revisions\/6675"}],"wp:attachment":[{"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=6664"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=6664"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=6664"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}