单元测试用例中的空@Autowired bean

Man*_*een 6 java junit spring unit-testing intellij-idea

我正在尝试自动连接一个 spring 管理的 bean 以在我的单元测试用例中使用。但是自动装配的 bean 始终为 null。下面是我的设置。

我的单元测试课

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = "classpath*:business-context-test.xml")
public class SMSGatewayTest {

    @Autowired
    @Qualifier("mySMSImpl")
    private ISMSGateway smsGateway;

        @Test
        public void testSendTextMessage() throws Exception {
          smsGateway.sendText(new TextMessage("TEST")); 
          //  ^___________ this is null, even though I have set ContextConfiguration 
        }

}
Run Code Online (Sandbox Code Playgroud)

春季管理豆

package com.myproject.business;

@Component("mySMSImpl")
public class MySMSImpl implements ISMSGateway {

    @Override
    public Boolean sendText(TextMessage textMessage ) throws VtsException {
          //do something
    }

}
Run Code Online (Sandbox Code Playgroud)

单元测试用例的上下文

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">


       <context:annotation-config/>
       <context:component-scan base-package="com.myproject.business"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

我看到了很多问题,所有问题都给出了我已经包含在我的代码中的答案。有人可以告诉我我错过了什么。我正在使用 intellij 14 来运行我的测试用例。

asg*_*asg 3

你有这样的代码:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = "classpath*:business-context-test.xml")
public class SMSGatewayTest {
   ..
   ..
}
Run Code Online (Sandbox Code Playgroud)

你真的想使用 MockitoJUnitRunner 因为我在课堂上没有看到更多的模拟。

请尝试运行 JUnit

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:business-context-test.xml")
public class SMSGatewayTest {
   ..
   ..
}
Run Code Online (Sandbox Code Playgroud)

编辑 -

@RunWith(SpringJUnit4ClassRunner.class)使使用 @ContextConfiguration(..) 声明的所有依赖项都可用到使用它的类。

例如,在您的情况下,您在类 SMSGateway 上有@RunWith(SpringJUnit4ClassRunner.class) 。因此,它使使用 @ContextConfiguration(locations = "classpath*:business-context-test.xml") 配置的 SMSGateway 的所有依赖项可用

这有助于在您的 SMSGateway 类中自动连接“smsGateway”。当您使用@RunWith(MockitoJUnitRunner.class)时,此依赖项不可用于自动装配,因此 spring 会抱怨。如果您在应用程序中使用 Mockito,则需要 MockitoJUnitRunner.class。由于您没有模拟任何类,因此现在不需要 MockitoJUnitRunner。

请查看 - Mockito、JUnit 和 Spring 以获取更多说明。

看看http://www.alexecollins.com/tutorial-junit-rule/。这将帮助您了解“@Runwith”和“@ContextConfiguration”注释如何在幕后工作。