Test void methods with Autowired classes

Viewed 1139

I am a beginner in Spring and I need to write test for this class if it calls methods:

class ClassOne {

    @Autowired
    AutowiredClass a1;

    @Autowired
    AutowiredClass a2;

    void methodOne() {
        a1.method1();    
    }

    void methodTwo() {
        a2.method2();
    }
}

I've tried to write test, but failed, got NPE:

class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;

    @Test
    public void testMethod1() {
        c1i.methodOne();  // <- NPE appears here..
        Mockito.verify(ClassOne.class, Mockito.times(1));
    }
}

Would be great to successfully test void methods.

3 Answers

You can verify that using a unit test:

@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest {

    @InjectMocks
    private ClassOne c1 = new ClassOne();

    @Mock
    private AutowiredClass a1;

    @Mock
    private AutowiredClass a2;

    @Test
    public void methodOne() {
        c1.methodOne(); // call the not mocked method
        Mockito.verify(a1).method1(); //verify if the a1.method() is called inside the methodOne
    }
}

ClassOne defines a spring bean. In order to Autowire the bean's fields you need a Spring Context.

If you want to test ClassOne as a SPRING BEAN, then you need to use SpringTest.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({MyConfig.class}) // Spring context config class
class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;
...
}

A ClassOne bean will be injected into the test suite c1i field.

Then you can spy on the field using mockito:

ClassOne cSpy = spy(c1i);

Then you can verify method calls on it :

verify(cSpy).someMethod(someParam);

Hope this helps

You are getting a NPE because the loaded context on your test case cannot find the autowired bean you mentioned. You should annotate the test class like so:

@RunWith(SpringRunner.class)
@SpringBootTest
class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;

    @Test
    public void testMethod1() {
        c1i.methodOne();  // <- NPE appears here..
        Mockito.verify(ClassOne.class, Mockito.times(1));
    }
}

Consider taking a look at: Similar NPE test error

Related