
在单元测试中,我们经常使用mocking框架(如mockito)来隔离被测代码,以确保测试的焦点仅在于当前的逻辑。然而,当被测类别时(thing)的内部方法(blogic)测试可能面临挑战,而不是通过依赖注入直接在内部创建依赖对象(如thingrandparent和thingparent)。
在原始测试代码中,Thingblogic方法的执行流程如下:
- ThingGrandParent tgp = fun(size);:blogic方法调用thing本身的fun方法,fun方法内部通过neww ThingGrandParent(size)创建了一个真实的ThingGrandParent实例。
- ThingParent tp = tgp.GpFun(size);:然后,这个真正的ThingGrandParent实例调用了GPFun方法,也在其内部通过了newnt ThingParent(y)创建了真实的ThingParent实例。
- st = tp.fetchSideThing();:最后,这个真实的ThingParent实例调用了fetchsidething方法。
问题是测试ThingTest中声明的问题@Mock ThingParent tp;和@Mock ThingGrandParent tgpp;这些模拟对象,在t.bLogic(4)执行过程中从未使用过。t的blogic方法始终操作自己创建的真实对象。因此,设置模拟对象tp的when(tgpp.GpFun(anyInt())).thenReturn(tp);虽然语法是正确的,但由于模拟对象tgpp从未被t使用,因此该行代码的设置失去了意义。
asssertequals(4, t.bLogic(4));实施后,由于tp(模拟对象)的fetchSidething()方法从未被调用,随后的verify(tp, times(1)).fetchSideThing();自然会失败,抛出Wanted but not invoked的错误。至于invocationtargetexception,它通常发生在反射调用方法中。如果该方法内部抛出异常,反射机制将将其包装成invocationtargetexception。在这种情况下,它可能间接表明blogic方法的内部执行过程与预期不一致,导致后续问题。
解决方案:正确模拟内部依赖性解决这类问题的核心是,当实施blogic方法时,我们需要让被测对象t使用我们提供的模拟对象,而不是它自己创建的真实对象。由于thing类没有提供依赖注入的接口(例如,通过构造函数或setter方法将thingggrandparent传输到thinggrandparent),我们需要使用mockito的spy功能来模拟thing对象本身的内部方法。
核心策略:模拟被测对象内部方法的调用- 将Thing对象声明为spy: t = spy(new Thing()); 这一步是正确的。spy允许我们部分模拟一个真实的对象,即模拟一些方法,而其他方法则正常执行。
-
模拟t的fun方法: 我们需要让T.bLogic()内部调用的t.fun()方法返回我们预期的模拟对象tgpp,而不是创建一个新的thingggrandparent。
when(t.fun(anyInt())).thenReturn(tgpp);
当t通过这行代码.bLogic()内部调用fun(size)它将不再创建新的thingGrandParent,而是直接获得我们预设的模拟对象tgpp。
-
GPFun模拟tgpp的方法: 现在t.bLogic()已经获得了模拟tgpp对象,我们需要确保tgpp.GpFun(size)调用还可以返回我们预设的模拟对象tp。
when(tgpp.GpFun(anyInt())).thenReturn(tp);
这样,t.bLogic()可获得模拟tp对象。
-
fetchSidething模拟tp的方法: 最后,我们需要确保模拟tp对象在调用fetchSidething()时返回符合测试预期的sidething实例。根据assertequals(4, t.bLogic(4));,我们期望Sidething.getWeight()返回4。
when(tp.fetchSideThing()).thenReturn(SideThing.get(4));
或者,如果Sidething的创建逻辑简单,也可以直接返回真实的Sidething实例:when(tp.fetchSideThing()).thenReturn(new SideThing(4));
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// 原始类定义(此处省略,与问题描述相同)
// ... SideThing, ThingGrandParent, ThingParent, Thing ...
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PrepareForTest({Thing.class, SideThing.class}) // PowerMock 用于处理更复杂的模拟场景,如静态、final、构造函数等
public class ThingTest {
@Mock
ThingParent tp;
@Mock
ThingGrandParent tgpp;
Thing t;
// 使用 MockitoRule 替代废弃的 MockitoAnnotations.initMocks()
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Before
public void setup() {
// MockitoAnnotations.initMocks(this); // 该方法已废弃,使用 @Rule 替代
t = spy(new Thing()); // t 它是一个真实的对象,但它的方法可以部分模拟
}
@Test
public void test1() throws Exception {
// 1. 模拟 t.fun() 方法,让它返回我们期望的模拟 tgpp 对象
when(t.fun(anyInt())).thenReturn(tgpp);
// 2. 模拟 tgpp.GpFun() 方法,让它返回我们期望的模拟 tp 对象
when(tgpp.GpFun(anyInt())).thenReturn(tp);
// 3. 模拟 tp.fetchSideThing() 方法,使其返回一个具有预期权重的重量 SideThing 对象
// 这样,t.bLogic() 最终会得到这个 SideThing,并调用其 getWeight()
when(tp.fetchSideThing()).thenReturn(SideThing.get(4));
// 执行被测方法
assertEquals(4, t.bLogic(4));
// 验证模拟对象的交互
verify(tp, times(1)).fetchSideThing();
verify(tgpp, times(1)).GpFun(anyInt()); // 也可以验证 tgpp 的调用
verify(t, times(1)).fun(anyInt()); // 也可以验证 t 的 fun 方法的调用
}
}Mockito 最佳实践的初始化
Mockitoanotionss在原始代码中使用.initMocks(this);,但是这种方法已经被标记为废弃。在现代Mockito和Junit的集成中,建议使用Mockitorule(Junito) 4)或者Mockitoextension(Junittitton) 5)Mock对象的初始化。
对于JUnit 4: 在测试类中添加@Rule注释和MockitoJunitt.rule():
import org.junit.Rule;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
public class ThingTest {
@Rule
public MockitoRule rule = MockitoJUnit.rule();
// ... 其他代码 ...
}
Mockitorule自动处理@Mock、@InitMocks不需要手动调用Spy等注释的初始化。
对于JUnit 5: 使用@ExtendWith(MockitoExtension.class):
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class ThingTest {
// ... 其他代码 ...
}Spy 与 InjectMocks 的选择
本例提到了spy和injectmocks的区别,以及如何选择。
- @Spy: 用于部分模拟真实对象。这意味着对象未被模拟的方法将执行其真实逻辑,而被模拟的方法将执行我们定义的行为。当被测对象内部创建其依赖性,或者您需要测试真实对象的复杂行为,但同时隔离其部分依赖性时,spy非常有用。在这种情况下,Thing t = spy(new Thing());这是正确的选择,因为它允许我们模拟t的fun()方法,而blogic()的其它部分正常执行。
- @InjectMocks: 用来创建一个类的例子,并尝试在这个例子中注入所有@Mock或@Spy注释的字段。它主要通过构造函数注入、setter注入或字段注入来工作。InjectMocks适用于通过依赖注入(而不是内部创建)获得其依赖性的被测类别。
在这种情况下,neww直接在Thing类内部调用 ThingGrandParent()和new ThingParent()为了创建依赖性,它没有thingGrandParent或thingParent字段,可以注入injectMocks。因此,injectMocks不适用于这里,spy是一个更合适的选择,因为它允许我们拦截和模拟fun()方法在thing对象内部的调用。
注意事项及总结- 依赖注入优先: 最佳实践是设计可测试的代码,即通过构造函数或setter方法依赖注入,直接注入Mock对象,简化测试。spy和powermock是不能重构代码的强大工具。
- PowerMock的使用: PowerMock (@RunWith(PowerMockRunner.class), @PrepareForTest) 它通常用于处理静态方法、final类/方法、构造函数或私有方法等Mockito无法直接模拟的场景。在这个例子中,尽管它是spy
以上是Mockito/PowerMock测试中依赖模拟的陷阱和解决方案的详细内容。请关注图灵教育的其他相关文章!