【问题标题】:The @Autowired field is null during tests with Junit, how can i mock/instantiate it?在使用 Junit 进行测试期间,@Autowired 字段为空,我如何模拟/实例化它?
【发布时间】:2020-04-06 14:52:31
【问题描述】:

我无权访问MyClass2 代码,也无法更改它。我如何模拟/实例化MyClass2 myClass2

类和代码测试:

@RunWith(JUnit4.class)//can't change thisone
public class MyTest
{
    @Autowired // or not, tried both ways
    MyClass testedInstance= new MyClass();
    @Test
    public void boot() throws Exception{
        testedInstance.boot();
        assertTrue(true);
    }
}

public class MyClass
{
    @Autowired 
    private MyClass2 myClass2;

    void boot()
    {
        myClass2.foo();//getting a null pointer here
    }
}

【问题讨论】:

标签: java spring spring-boot junit autowired


【解决方案1】:

首先,您需要使用以下内容注释您的测试类:

@RunWith( SpringJUnit4ClassRunner.class )

然后关于MyClass:

@Autowired 
MyClass testedInstance;

您需要删除 = new MyClass();,因为您正在自动装配它。

那么从现在开始你正在注入MyClass,如果有可用于注入的 MyClass2 实例,它将被注入 MyClass,如果没有,则不会。

您需要配置您的应用程序上下文,以便这样的 bean MyClass2 存在,

【讨论】:

    【解决方案2】:

    您可以查看原始答案

    https://stackoverflow.com/a/71591567/5108695

    但这是一个很常见的问题,所以我也在这里发布了答案

    在我看来,我们正在编写单元测试用例,我们不应该为了测试一段代码而初始化 Spring 上下文。

    所以,

    我使用 Mockito 在我的主要目标测试类中模拟 Autowired bean,并将这些模拟 bean 注入到我的主要测试类 Object 中

    可能听起来令人困惑,请参阅以下示例 ?

    我使用的依赖项

        testImplementation("org.mockito:mockito-core:2.28.2")
        testImplementation("org.mockito:mockito-inline:2.13.0")
        testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
        testImplementation("org.mockito:mockito-junit-jupiter:4.0.0")
    

    我的主要课程是数学,而计算器 bean 是自动装配的

    
    class Maths{
    
       @Autowired Calculator cal;
    
       .........
       .........
    
       public void randomAddMethod(){
          cal.addTwoNumbers(1,2); // will return 3;
       }
    }
    
    

    测试类

    
    @ExtendWith(MockitoExtension.class)
    
    class MathsTest{
    
       @Mock(answer = Answers.RETURNS_DEEP_STUBS) Calculator cal;
    
       @InjectMocks Maths maths = new Maths();
    
       @Test testMethodToCheckCalObjectIsNotNull(){
          maths.randomAddMethod();
       }
    }
    
    

    现在cal 在数学类中不会为空,并且会按预期工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 2013-05-01
      相关资源
      最近更新 更多