首页 > 解决方案 > 使用 Autowired 类测试 void 方法

问题描述

我是 Spring 的初学者,如果它调用方法,我需要为这个类编写测试:

class ClassOne {

    @Autowired
    AutowiredClass a1;

    @Autowired
    AutowiredClass a2;

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

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

我试过写测试,但失败了,得到了 NPE:

class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;

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

成功测试 void 方法会很棒。

标签: javaspringtesting

解决方案


您可以使用单元测试来验证:

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

推荐阅读