简体   繁体   English

spring 和 junit4 测试 class 中的私有方法

[英]spring and junit4 to test a private method in class

I have two spring bean class ServiceA and ServiceB.我有两个 spring bean class ServiceA 和 ServiceB。 ServiceA dependents ServiceB. ServiceA 依赖 ServiceB。 Show the code:显示代码:

@Service // spring IOC annotation
public class ServiceA {

   @Autowired
   private ServiceB sb;

   // other code
   
   private void aMethod() {
      // other code
      sb.bMethod();
      // other code
   }

}

I write the ServiceA`s unit class by Junit4, flowing code:我用 Junit4 编写 ServiceA 的单元 class,流式代码:

@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);
   }
}

I run the ServiceATest, when I debug the ServiceATest#aMethodTest(), the object 'sa' is a CGLIB proxy object.我运行 ServiceATest,当我调试 ServiceATest#aMethodTest() 时,object 'sa' 是 CGLIB 代理 object。 But I debug the ServiceA#aMethod(), the 'sb' is null.但我调试 ServiceA#aMethod(),'sb' 是 null。

I am confused.我很困惑。 The object 'sa' is from Spring Bean Container, so it must be a complete object with Spring-DI. object 'sa' 来自 Spring Bean Container,因此它必须是带有 Spring-DI 的完整 object。 Why it`s field is null when i call sa.aMethod() method?当我调用 sa.aMethod() 方法时,为什么它的字段是 null?

Not the answer you may be looking for, but private methods are supposed to be supporter methods and not need to be tested.不是您可能正在寻找的答案,但私有方法应该是支持者方法,不需要进行测试。 Incase if you have written private method that needs unit test then PowerMock or PowerMockito will provide much better tests than java reflection.如果您编写了需要单元测试的私有方法,那么 PowerMock 或 PowerMockito 将提供比 java 反射更好的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM