如何使用JUnit测试具有内部私有方法、字段或嵌套类的类?
仅仅为了能够运行测试而更改方法的访问修饰符似乎是不好的。
如何使用JUnit测试具有内部私有方法、字段或嵌套类的类?
仅仅为了能够运行测试而更改方法的访问修饰符似乎是不好的。
当前回答
正如其他人所说。。。不要直接测试私有方法。以下是一些想法:
保持所有方法的规模和重点(易于测试,易于发现错误)使用代码覆盖工具。我喜欢Cobertura(哦,快乐的一天,它看起来像是一个新版本!)
在单元测试上运行代码覆盖率。如果您发现方法没有经过充分测试,请添加到测试中以提高覆盖率。目标是100%的代码覆盖率,但要意识到你可能无法做到这一点。
其他回答
今天,我推出了一个Java库来帮助测试私有方法和字段。它的设计考虑到了Android,但它确实可以用于任何Java项目。
如果您有一些带有私有方法、字段或构造函数的代码,可以使用BoundBox。它正是你想要的。下面是一个测试示例,它访问Android活动的两个私有字段来测试它:
@UiThreadTest
public void testCompute() {
// Given
boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());
// When
boundBoxOfMainActivity.boundBox_getButtonMain().performClick();
// Then
assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}
BoundBox使测试私有/受保护的字段、方法和构造函数变得容易。你甚至可以访问被继承隐藏的东西。实际上,BoundBox打破了封装。它会让您通过反射访问所有这些内容,但在编译时会检查所有内容。
它非常适合测试一些遗留代码。小心使用。;)
如果您确实需要直接测试私有方法/类等,那么可以使用其他答案中已经提到的反射。然而,如果说到这一点,我宁愿使用框架提供的实用程序类,而不是直接处理反射。例如,对于Java,我们有:
Spring框架中的ReflectionUtilsJUnit中的ReflectionUtils
关于如何使用它们,你可以在网上找到很多文章。我特别喜欢这个:
org.springframework.util.ReflectionUtils的Java代码示例
下面的ReflectionTestUtil可以通用地用于测试私有方法的原子性。
import com.google.common.base.Preconditions;
import org.springframework.test.util.ReflectionTestUtils;
/**
* <p>
* Invoker
* </p>
*
* @author
* @created Oct-10-2019
*/
public class Invoker {
private Object target;
private String methodName;
private Object[] arguments;
public <T> T invoke() {
try {
Preconditions.checkNotNull(target, "Target cannot be empty");
Preconditions.checkNotNull(methodName, "MethodName cannot be empty");
if (null == arguments) {
return ReflectionTestUtils.invokeMethod(target, methodName);
} else {
return ReflectionTestUtils.invokeMethod(target, methodName, arguments);
}
} catch (Exception e) {
throw e;
}
}
public Invoker withTarget(Object target) {
this.target = target;
return this;
}
public Invoker withMethod(String methodName) {
this.methodName = methodName;
return this;
}
public Invoker withArguments(Object... args) {
this.arguments = args;
return this;
}
}
Object privateMethodResponse = new Invoker()
.withTarget(targetObject)
.withMethod(PRIVATE_METHOD_NAME_TO_INVOKE)
.withArguments(arg1, arg2, arg3)
.invoke();
Assert.assertNotNutll(privateMethodResponse)
如果您的测试类与应该测试的类在同一个包中呢?
当然,在另一个目录中,源代码使用src&classes,测试类使用test/src和test/classes。让类和测试/类位于类路径中。
PowerMockito就是为此而生的。
使用Maven依赖项:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
那你就可以了
import org.powermock.reflect.Whitebox;
...
MyClass sut = new MyClass();
SomeType rval = Whitebox.invokeMethod(sut, "myPrivateMethod", params, moreParams);