【问题标题】:JMockit with Spring autowire not working带有 Spring 自动装配的 JMockit 不起作用
【发布时间】:2015-09-24 20:39:17
【问题描述】:

我正在使用 JMockit 来测试一个正在自动装配的类(弹簧)。从这个post,我可以理解我必须手动将模拟实例注入ClassToBeTested。即使我这样做,我也会在Deencapsulation.setField(classUnderTest, mockSomeInterface); 行遇到NullPointerEx,因为classUnderTest 和mockSomeInterface 都是null。但是,如果我在mockSomeInterface 上使用@Autowire,它会自动正确连接。

要测试的类:

@Service
public class ClassToBeTested implements IClassToBeTested {

 @Autowired
 ISomeInterface someInterface;

 public void callInterfaceMethod() {
  System.out.println( "calling interface method");
  String obj = someInterface.doSomething();
 }
}

测试用例:

public class ClassToBeTestedTest  {

@Tested IClassToBeTested classUnderTest;

@Mocked ISomeInterface mockSomeInterface;

public void testCallInterfaceMethod(){
  Deencapsulation.setField(classUnderTest, mockSomeInterface);
  new Expectations() { {
     mockSomeInterface.doSomething(anyString,anyString); result="mock data";     
  }};
 // other logic goes here
 }
}

【问题讨论】:

    标签: java spring jmockit


    【解决方案1】:

    使用最新版本的 JMockit 尝试以下操作(请注意,链接的问题来自 2010 年,从那时起该库已经发展了很多):

    public class ClassToBeTestedTest
    {
        @Tested ClassToBeTested classUnderTest;
        @Injectable ISomeInterface mockSomeInterface;
    
        @Test
        public void exampleTest() {
            new Expectations() {{
                mockSomeInterface.doSomething(anyString, anyString); result = "mock data";
            }};
    
            // call the classUnderTest
        }
    }
    

    【讨论】:

    • 如何在测试类中使用 spring @Autowired 字段来做到这一点?
    猜你喜欢
    • 2014-09-01
    • 2017-01-19
    • 2018-12-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多