简体   繁体   中英

JUNIT Autowired instance is always null

I am trying to write test case for the below class where everytime myConfig instance is coming as null. Is there any way to pass the autowired instance.

public class MyClass {

@Autowired
MyConfig myConfig ;

public Properties getUnAckMessage(String queueName) {
    Properties prop=new Properties() 
        URL url = new URL(StringUtils.join(myConfig.getQueueHost(),
                    myConfig.getQueueURL(),myConfig.getQueueVm(),queueName));

    return prop;            
    }

public  Properties request(String queue) {           
        return getUnAckMessage(queue);
    }
}

public class Main {

  public void method() {
  MyClass myClass=new MyClass();
  myClass.getUnAckMessage("test");
  }
 }

Test case

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

 @MockBean
MyConfig myConfigReader;




@Test
    public void testMyClass() {      
        MyClass  propertiesExchangeManager1 = new MyClass ();
        propertiesExchangeManager1.request("test");
      } 
    }

You must activate Spring for your test if you want spring to autowire. For exemple:

@RunWith(SpringRunner.class)
public class Test {

    @Autowired private MyClass myClass

    @Test
    public void test() {
        ///...
    }
}

EDIT: If you instanciate the class MyClass by yourself, Spring cannot inject needed classes. You should modify your test like this:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

 @MockBean
MyConfig myConfigReader;

@Autowired
MyClass propertiesExchangeManager1;


@Test
    public void testMyClass() {      
        propertiesExchangeManager1.request("test");
      } 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM