Null @Autowired beans in unit test case

I am trying to do an automatic spring bean wiring for use in my unit test case. But an autwired bean is always null. Below are the settings.

my unit test class

@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 bean

package com.myproject.business;

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

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

}

context for unit test case

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

I saw a lot of questions, and all give answers that I have already included in my code. Can someone tell me what I am missing. I am using intellij 14 to run my test case.

+4
source share
2 answers

You have a code like this:

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

Are you really using MockitoJUnitRunner because I no longer see any mockery of the class in me.

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 . MockitoJUnitRunner.class, Mockito . , MockitoJUnitRunner .

, Mockito, JUnit Spring .

http://www.alexecollins.com/tutorial-junit-rule/. , "@Runwith" "@ContextConfiguration" .

+3

Bean

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

Qualifier ? ISMSGateway?

0

All Articles