【发布时间】:2020-12-15 14:47:30
【问题描述】:
我有两个 Spring bean 类 ServiceA 和 ServiceB。 ServiceA 依赖 ServiceB。显示代码:
@Service // spring IOC annotation
public class ServiceA {
@Autowired
private ServiceB sb;
// other code
private void aMethod() {
// other code
sb.bMethod();
// other code
}
}
我用Junit4编写ServiceA的单元类,流式代码:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ServiceATest {
@Autowired
private ServiceA sa;
@Test
public void aMethodTest() {
Method method = ReflectionUtils.findMethod(ServiceA.class, "aMethod");
method.setAccessible(true);
ReflectionUtils.invokeMethod(method, sa);
}
}
我运行 ServiceATest,当我调试 ServiceATest#aMethodTest() 时,对象“sa”是一个 CGLIB 代理对象。但我调试ServiceA#aMethod(),'sb'为空。
我很困惑。对象 'sa' 来自 Spring Bean Container,因此它必须是带有 Spring-DI 的完整对象。为什么我调用 sa.aMethod() 方法时它的字段为空?
【问题讨论】:
-
因为您是在代理而不是真实对象上调用它。此外,您不应该测试私有方法,而是测试调用该私有方法的实际公共方法。
-
谢谢。但我还有一个问题:为什么不推荐测试私有方法?还是我对“私有方法”有错误的想法?
-
因为它们是私有的并且不应该被直接调用。它们被称为公共方法的一部分。公共方法是您应该测试的方法,并且可能使用不同的输入/场景,以便您测试所有可能的排列。
标签: java spring spring-boot