考虑代码:
abstract public class TigerFinderPage extends TigerPage
private Manager manager;
protected Manager getTiger()
{
// If we haven't already done so, get the tiger.
if (tiger== null) {
try {
tiger= EntityResolution.getTigerFromName(ResTools.resolveNoTranslation(getConfigBundle(), "tiger", ""));
} catch (Exception e) {
LogTools.error(logger, null, e);
return null;
}
}
return tiger;
}
尝试1:
public class TigerFinderPageTest {
private TigerFinderPage tigerFinderPage;
@Before
public void setUp() throws Exception {
TigerFinderPage = new TigerFinderPage () {
@Override
protected ResourceProvider getBundle() {
return null;
}
@Override
protected ResourceProvider getConfigBundle() {
return null;
}
};
}
@Test
public void testTigerManager(){
assertNull(tigerFinderPage.getTiger());
}
}
如何在受保护的方法处于不同的包中时对其进行测试?我尝试过使用反射,但在这种情况下不知道如何实现它。
答案 0 :(得分:1)
测试非公开成员会将您的测试与您的实现联系起来,并使重构变得更加困难。
如果它足够重要,无法通过公共接口进行测试,那么它必须是独立的功能,可以存在于自己的类中{la-{3}}
在这种情况下,我有一个单独的类和LazyTigerFactory
的测试:
public final class LazyTigerFactory {
private Manager manager;
public Manager getTiger()
{
// If we haven't already done so, get the tiger.
if (tiger == null) {
try {
tiger= EntityResolution.getTigerFromName(ResTools.resolveNoTranslation(getConfigBundle(), "tiger", ""));
} catch (Exception e) {
LogTools.error(logger, null, e);
return null;
}
}
return tiger;
}
}
然后在课堂上使用它:
abstract public class TigerFinderPage extends TigerPage
private final LazyTigerFactory tigerFactory = new LazyTigerFactory();
protected Manager getTiger(){
return tigerFactory.getTiger();
}
TigerFinderPage
测试混乱。LazyTigerFactory
。TigerFinderPage
的直接依赖关系较少。TigerFinderPage
更小,更少懒惰/实体锅炉板混乱了这个班级真正做的事情(它的唯一责任)。答案 1 :(得分:0)
一个答案是遵循JUnit的最佳实践并同时拥有生产代码和代码以在同一个包中对其进行测试,以便允许访问protected
成员,但< strong>在不同的源文件夹,因此非生产代码不会干扰生产代码。例如,在maven的结构中:
-- src
+-- main
+-- java
+-- org
+-- mypackage # Production code for org.mypackage
+-- test
+-- java
+-- org
+-- mypackage # Testing code for org.mypackage
如果这不是一个选项,您可以继承抽象类并提高所述方法的可见性,这样测试就可以访问它:
public class TigerFinderPageTest {
public static class TigerFinderPageDummy extends TigerFinderPage {
@Override
protected ResourceProvider getBundle() {
return null;
}
@Override
protected ResourceProvider getConfigBundle() {
return null;
}
/** Note this method is PUBLIC */
@Override
public Manager getTiger() {
return super.getTiger();
}
}
private TigerFinderPageDummy tigerFinderPage;
@Before
public void setUp() throws Exception {
tigerFinderPage = new TigerFinderPageDummy();
}
@Test
public void testTigerManager(){
assertNull(tigerFinderPage.getTiger());
}
}