java 测试使用Autowired对象的Spring服务类

ukxgm1gy  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(152)

我必须测试一个使用Autowired对象的Spring服务,请参见以下代码:

@Service
public class MyService {

    @Autowired
    ExternalService externalService;

    public String methodToTest(String myArg) {
        String response = externalService.call(myArg);
        // ...
        return ...;
    }

在我的测试类中,我尝试使用Mockito模拟externalService的call方法,如下所示:

@ExtendWith(MockitoExtension.class)
public class MySeviceTest {
    @Mock
    private ExternalService externalService = Mockito.mock(ExternalService.class);
    private MySevice mySevice = Mockito.spy(new MySevice());

    @Test
    public void methodToTest_Test() {
        Mockito.when(externalService.call(anyString())).thenReturn(anyString());
        // ...
    }
}

问题出在类MyService的运行时,因为externalService对象是空的,结果我得到了空指针异常,那么,写这种类型测试的正确方法是什么呢?

kmbjn2e3

kmbjn2e31#

由于没有设置属性'externalService',您会得到一个null指针异常。@Autowired仅在使用Spring运行时有效。对于您的测试,您必须自己注入模拟:

@ExtendWith(MockitoExtension.class)
public class MySeviceTest {
    @Mock
    private ExternalService externalService = Mockito.mock(ExternalService.class);
    private MySevice mySevice = Mockito.spy(new MySevice());

    @Test
    public void methodToTest_Test() {
        myService.externalService = externalService //inject your mock via the property
        Mockito.when(externalService.call(anyString())).thenReturn(anyString());
        // ...
    }
}

相关问题