
本文介绍了如何使用 JMockit 框架在测试类中自动装配带有 Mock 注入的依赖。通过 @Tested 和 @Injectable 注解,JMockit 可以自动创建实例并注入 Mock 对象,从而简化单元测试的编写。文章提供了详细的代码示例和注意事项,帮助读者理解和应用 JMockit的自动装配功能。
在单元测试中,经常需要模拟某些依赖项的行为,以便隔离被测试的代码并验证其功能。JMockit 是一个强大的 Java Mocking 框架,它提供了丰富的功能来创建和管理 Mock 对象。本文将介绍如何使用 JMockit 自动装配带有 Mock 注入的依赖,从而简化测试代码的编写。
使用 @Tested 和 @Injectable 注解
JMockit 提供了 @Tested 和 @Injectable 注解来实现自动装配。@Tested 注解用于标记需要测试的类,JMockit 会自动创建该类的实例。@Injectable 注解用于标记需要 Mock 的依赖项,JMockit 会创建这些依赖项的 Mock 对象,并将其注入到 @Tested 标记的类的实例中。
考虑以下示例:
class MyReusableClassForTesting {
private ClassA attribute;
public MyReusableClassForTesting(ClassA attribute) {
this.attribute = attribute;
}
public String doSomething() {
return attribute.getValue();
}
}
class ClassA {
public String getValue() {
return "real value";
}
}现在,我们想要编写一个测试类来测试 MyReusableClassForTesting,并模拟 ClassA 的行为。可以使用以下代码:
import org.junit.jupiter.api.Test;
import mockit.Injectable;
import mockit.Tested;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import mockit.Expectations;
class MyTestClass {
@Tested
MyReusableClassForTesting instance;
@Injectable
ClassA attribute;
@Test
void testDoSomething() {
assertNotNull(instance);
new Expectations() {{
attribute.getValue(); result = "mocked value";
}};
String result = instance.doSomething();
assertEquals("mocked value", result);
}
@Test
public void testCtor() {
assertNotNull(instance);
}
}在上面的代码中,@Tested 注解标记了 MyReusableClassForTesting,JMockit 会自动创建该类的实例。@Injectable 注解标记了 ClassA,JMockit 会创建 ClassA 的 Mock 对象,并将其注入到 MyReusableClassForTesting 的实例中。
testDoSomething 方法使用 Expectations 块来定义 attribute.getValue() 方法的行为,使其返回 "mocked value"。然后,调用 instance.doSomething() 方法,并断言其返回值是否为 "mocked value"。
testCtor方法用于确保JMockit正常工作。如果此测试失败,则可能是由于未添加JavaAgent。
注意事项
- 确保在构建脚本(如 build.gradle 或 pom.xml)和 IDE 中都添加了 JMockit 的 Java Agent。
- 如果 @Tested 标记的类的构造函数需要参数,或者有需要自动装配的依赖项,可以使用 @Injectable 注解来提供这些依赖项的 Mock 对象。
- 可以使用简单的测试方法(如 testCtor)来验证 JMockit 是否正常工作。
总结
通过使用 JMockit 的 @Tested 和 @Injectable 注解,可以轻松地实现自动装配带有 Mock 注入的依赖。这可以大大简化单元测试的编写,提高测试效率。记住添加JavaAgent, 否则JMockit无法工作.










