我试图使用Java Reflection获取和调用驻留在不同类中的受保护方法以及不同的包.
包含受保护方法的类:
package com.myapp;
public class MyServiceImpl {
protected List<String> retrieveItems(String status) {
// Implementation
}
}
Run Code Online (Sandbox Code Playgroud)
通话课程:
package xxx.myapp.tests;
import com.myapp.MyServiceImpl;
public class MyTestCase {
List<String> items;
public void setUp() throws Exception {
MyServiceImpl service = new MyServiceImpl();
Class clazz = service.getClass();
// Fails at the next line:
Method retrieveItems = clazz.getDeclaredMethod("retrieveItems");
// How to invoke the method and return List<String> items?
// tried this but it fails?
retrieveItems.invoke(clazz, "S");
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抛出此异常:
java.lang.NoSuchMethodException: com.myapp.MyServiceImpl.retrieveItems()
Run Code Online (Sandbox Code Playgroud) 关于私有方法测试的意义有不同的意见,例如,这里和这里.我个人认为这是有道理的,问题是如何正确地做到这一点.在C++中你可以使用#definehack或者使用测试类friend,在C#中有InternalsVisibleToAttribute,但是在Java中我们必须使用反射或使它们"可见以进行测试"并对其进行注释以使意图清晰.两者的缺点应该非常清楚.
我认为应该有更好的东西.从...开始
public class Something {
private int internalSecret() {
return 43;
}
}
Run Code Online (Sandbox Code Playgroud)
能够在测试代码中调用私有方法会很好
@MakeVisibleForTesting Something something = new Something();
Assert.assertEquals(43, something.internalSecret());
Run Code Online (Sandbox Code Playgroud)
这里的注释会静默地将所有调用转换为something使用反射的私有方法.我想知道龙目岛是否可以做到(并会问作者).
做这么多魔术很可能证明太复杂了,无论如何它都需要一些时间,所以我正在寻找一些替代方案.也许用类似的东西@Decapsulate来注释正在测试的类,并使用注释处理器来生成Decapsulated_Something类似的类
public class Decapsulated_Something {
public Decapsulated_Something(Something delegate) {
this.delegate = delegate
}
public boolean internalSecret() {
// call "delegate.internalSecret()" using reflection
}
...
}
Run Code Online (Sandbox Code Playgroud)
这将允许使用
Decapsulated_Something something = new Decapsulated_Something(new Something());
Assert.assertEquals(43, …Run Code Online (Sandbox Code Playgroud) 我的Java应用程序由两部分组成:
对于1.我使用JUnit进行单元测试,但是你会为2做什么?
如何为命令行界面创建自动化测试?
我开始在我的项目中使用JUnit和Mockito,我很快注意到的是我最终将我的私有方法转换为public以便从测试类中加入,这是一个糟糕的解决方案.
有时只测试公共方法就足够了,但有时我也想测试一些内部方法.这有解决方法吗?例如,一个特殊的注释,允许JUnit将私有方法模拟为公共或类似的东西?
java ×5
junit ×2
reflection ×2
testing ×2
unit-testing ×2
mocking ×1
private ×1
protected ×1
tdd ×1