在将成员变量替换为Mock对象之前,需要先判断该成员变量目前是否已经是Mock对象,若已经是Mock对象,需要直接对该Mock对象进行Stub;若每次都生成新的Mock对象进行替换,会将之前的Mock对象的Stub操作覆盖。可以参考示例代码TestReplaceUtil类的replaceMockMember()/replaceSpyMember(),将指定对象中的指定类型成员变量替换为Mock/Spy对象,且可以防止之前设置的覆盖Stub操作。
被测试类为TestServiceB1Impl,在其中引用了TestServiceA1Impl类的实例,test1()与test3()方法分别调用TestServiceA1Impl类的同名方法。
在对TestServiceB1Impl类实例中的TestServiceA1Impl类实例的test1()方法进行Stub时,生成了TestServiceA1接口的Mock对象,对其test1()方法进行Stub,再将TestServiceB1Impl类实例中的TestServiceA1Impl类实例替换为Mock对象。
在对TestServiceB1Impl类实例中的TestServiceA1Impl类实例的test3()方法进行Stub时,生成了TestServiceA1接口的Mock对象,对其test3()方法进行Stub,再将TestServiceB1Impl类实例中的TestServiceA1Impl类实例替换为Mock对象。
以上操作导致TestServiceB1Impl类实例中的TestServiceA1Impl类实例的Mock对象被替换为最后一次生成的Mock对象,仅包含对test3()方法的Stub,对test1()方法的Stub已被覆盖。可参考示例TestSpMockMemberOfM4Run、TestSpMockMemberOfM4Mock类。