Null @Autowired bean在单元测试用例中

时间:2016-05-11 11:41:12

标签: java spring unit-testing intellij-idea junit

我正在尝试自动连接一个spring managed Bean,以便在我的单元测试用例中使用。但autowired 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 
        }

}
  

spring managed bean

package com.myproject.business;

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

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

}
  

单元测试用例的上下文

<?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>

我已经看到了很多问题,而且所有问题都已经提供了我已经在我的代码中加入的答案。有人可以告诉我我错过了什么。我正在使用intellij 14运行我的测试用例。

2 个答案:

答案 0 :(得分:3)

你有这样的代码:

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

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

请尝试使用类似

运行JUnit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:business-context-test.xml")
public class SMSGatewayTest {
   ..
   ..
}

编辑 -

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

例如,在您的情况下,您在类上有 @RunWith(SpringJUnit4ClassRunner.class) - SMSGateway。所以它使所有那些依赖于SMSGateway的依赖项都是使用@ContextConfiguration配置的(locations =“classpath *:business-context-test.xml”)

这有助于在您的班级SMSGateway中自动加载“smsGateway”。当您使用 @RunWith(MockitoJUnitRunner.class)时,此依赖项无法用于自动装配,因此Spring抱怨。如果您在应用程序中使用Mockito,则需要MockitoJUnitRunner.class。由于您没有嘲笑任何课程,因此截至目前您不需要MockitoJUnitRunner。

请看一下 - Mockito, JUnit and Spring   更多澄清。

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

答案 1 :(得分:0)

Bean名称中有一个额外的空格

@Component("mySMSImpl ")
@Qualifier("mySMSImpl")

在这种情况下,为什么要使用Qualifier注释?是否存在ISMSGateway接口的多个实现?

相关问题