Java 使用自动连接类测试void方法
我是Spring的初学者,如果该类调用方法,我需要为此类编写测试:Java 使用自动连接类测试void方法,java,spring,testing,Java,Spring,Testing,我是Spring的初学者,如果该类调用方法,我需要为此类编写测试: class ClassOne { @Autowired AutowiredClass a1; @Autowired AutowiredClass a2; void methodOne() { a1.method1(); } void methodTwo() { a2.method2(); } } 我尝试编写测试,但失
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));
}
}
ClassOneTest类{
@自动连线
classone接口c1i;
@试验
公共void testMethod1(){
c1i.methodOne();//您将获得一个NPE,因为您的测试用例上加载的上下文找不到您提到的自动连接bean。您应该像这样注释测试类:
@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));
}
}
@RunWith(SpringRunner.class)
@春靴测试
类一级测试{
@自动连线
classone接口c1i;
@试验
公共void testMethod1(){
c1i.methodOne();//ClassOne定义了一个spring bean。为了自动连接bean的字段,您需要一个spring上下文
如果您想将ClassOne作为Springbean进行测试,那么您需要使用SpringTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({MyConfig.class}) // Spring context config class
class ClassOneTest {
@Autowired
ClassOneInterface c1i;
...
}
一个ClassOne bean将被注入到testsuitec1i字段中
然后,您可以使用mockito监视现场:
ClassOne cSpy = spy(c1i);
然后您可以验证对它的方法调用:
verify(cSpy).someMethod(someParam);
希望这对您有所帮助您可以使用单元测试验证:
@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
}
}
有用链接+1