如何使用Mockito模拟内部类实例


@ConfigurationProperties(prefix= 'app')
@Getter @Setter
public class AppConfig{
private ExternalService externalService=new ExternalService();
@Getter @Setter
public static class ExternalService{
private String url;
private String authToken;
}
}

我使用AppConfig的服务。

@Service
@AllArgsConstructor
public class ExternalService{
private final AppConfig appConfig;
public boolean isAuthorize(String token){
String authUrl=appConfig.getExternalService().getUrl();
boolean isAuthorize= //External Apis call
return isAuthorize;
}
}

ExternalService 的测试等级

@ExtendWith(MockitoExtension.class)
class ExternalTestService{
@Mock
private AppConfig AppConfig;

@Mock
private AppConfig.ExternalService externalSeriveConfig;
@InjectMocks
private ExternalService externalService;
@Test
public void shouldAuthorize(){
//Null Pointer exception for AppConfig.getExternalService() 
Mockito.when(AppConfig.getExternalService().getUrl()).thenReturn("123456");
Assertions.assertEquals(externalService.isAuthorize(),true);
}

如果我模拟shouldAuthorize内部的GradingProperties.CentralServiceConfig,则它工作正常,但在ExternalService处获得Assertions.assertEquals时会获得NullPointerException(字符串authUrl=appConfig.getExternalService((.getUrl((;(像

@Test
public void shouldAuthorize(){
AppConfig.ExternalService externalMock=Mockito.mock(AppConfig.ExternalService.class);

Mockito.when(externalMock.getUrl()).thenReturn("123456");
Assertions.assertEquals(externalService.isAuthorize(),true);
}

如何模拟并使此代码可运行

当您有一个链式方法调用时,您需要确保chaied调用的每个部分都返回非null结果。

Mockito.when(AppConfig.getExternalService().getUrl()).thenReturn("123456");

您还没有清除对AppConfig的任何调用,因此AppConfig.getExternalService()返回null。

您需要:

Mockito.when(AppConfig.getExternalService()).thenReturn(externalSeriveConfig);
Mockito.when(AppConfig.getExternalService().getUrl()).thenReturn("123456");

或者更好:

Mockito.when(AppConfig.getExternalService()).thenReturn(externalSeriveConfig);
Mockito.when(externalSeriveConfig.getUrl()).thenReturn("123456");

最新更新