0

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");
      } 
    }
user3428736
  • 864
  • 2
  • 13
  • 33

1 Answers1

4

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

@RunWith(SpringRunner.class)
public class Test {

    @Autowired private MyClass myClass

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

If you instantiate the class MyClass by yourself, Spring cannot inject the 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");
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
  • I am getting the below exception org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.test.MyClassTest': Unsatisfied dependency expressed through field 'myConfigReader'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.reader.MyConfigReader' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: – user3428736 Nov 04 '19 at 11:32
  • This exception states that a bean of type MyConfigReader can't be autowired. Be sure this class is annotated with '@Service' '@Component' or similar annotation for spring to be able to create an instance. – Oreste Viron Nov 04 '19 at 11:36
  • It is present in the class but still the exception is coming and btw it is consumed by MyClass but not the same case in test class and also Is it possible to use Mockito. – user3428736 Nov 04 '19 at 11:50
  • Yes, you can use mockito with '@Mock' and '@InjectMocks'. Check https://www.mkyong.com/spring-boot/spring-boot-junit-5-mockito/ – Oreste Viron Nov 04 '19 at 11:55
  • Edited my post. – Oreste Viron Nov 04 '19 at 13:53