我是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方法将非常有用。
最佳答案
您可以使用单元测试来验证:
@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
}
}