Search code examples
spring-bootjunitmockitojunit5spring-boot-test

How to mock Inner class instance using 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;
    }
}

Service where I am using 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;
    }
}

Test class for 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);
}

If I mock GradingProperties.CentralServiceConfig inside shouldAuthorize then it is working fine but getting NullPointerException while Assertions.assertEquals at ExternalService(String authUrl=appConfig.getExternalService().getUrl();) like

@Test
public void shouldAuthorize(){
    AppConfig.ExternalService externalMock=Mockito.mock(AppConfig.ExternalService.class);
    
    Mockito.when(externalMock.getUrl()).thenReturn("123456");
    Assertions.assertEquals(externalService.isAuthorize(),true);
}

How to mock and make this code runnable


Solution

  • When you have a chained method call, you need to make sure that each part of the chaied call returns non-null result.

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

    You haven't stubbed any calls on AppConfig, so AppConfig.getExternalService() returns null.

    You need:

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

    or, even better:

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