Получение NullPointerException во время насмешки в SpringBoot - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь написать тестовый пример Junit для одного из классов.Но получая ошибку при попытке сделать это,

Тестовый класс выглядит следующим образом -

public class IntegratorClassTest{
    @InjectMocks    
    IntegratorClass integratorClass;

    @Mock
    RequestClass requestClass;

    @Mock
    ContentList contentResponse;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void getCmsOffersTest()throws Exception{
        ContentService contentService = Mockito.mock(ContentService.class);
        RequestClass requestClass = Mockito.mock(RequestClass.class);
        ContentList contentResponse = getContentList();
        when(contentService.getContentCollection()).thenReturn(contentResponse);

        Validator validator = Mockito.mock(Validator.class);
        List<OfferDetails> offerList = new ArrayList<OfferDetails>();
        Mockito.doNothing().when(validator).validateData(offerList);

        List<OfferDetails> offerListResult = integratorClass.getCmsOffers(contentService, requestClass);
        assertTrue(offerListResult.size()>0);
    }
}

А класс реализации выглядит примерно так:

public class IntegratorClass {
    private static final Logger LOGGER = LoggerFactory.getLogger(IntegratorClass.class);

    @Autowired
    Validator validator;

    public List<OfferDetails> getCmsOffers(ContentService contentService,RequestClass requestClass)throws Exception{
        LOGGER.info("Entered method getCmsOffers to get the list of offers from CMS");
        List<OfferDetails> offerList = new ArrayList<OfferDetails>();
        ContentList contentResponse = null;
        try 
        {
            contentResponse = contentService.getContentCollection();
            offerList = getOfferListFromCmsResponse(contentResponse, requestClass);

            LOGGER.info("Total number of active offers we got from CMS are -" + offerList.size());
        }catch (Exception e)
        {
            ErrorResponse errorResponse = PromotionalOffersUtilities.createErrorResponse("500", e.getMessage(),"Getting error while fetching content from CMS - getCmsOffers", ErrorResponse.Type.ERROR);
            LOGGER.error("Getting error while fetching content from CMS with Error Message: " + e.getMessage());
            throw new ServiceException(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        //failing here
        validator.validateData(offerList);
        LOGGER.info("Exiting method getCmsOffers");

        return offerList;
    }
}

Когда язапустил его в режиме отладки am ошибка для строки validator.validateData(offerList);.

Возвращается "NullPointerException".

1 Ответ

0 голосов
/ 05 декабря 2018

Вам нужно включить Validator при моделировании зависимостей, чтобы он был внедрен в тестируемый объект

@Mock
Validator validator;

Также при организации поведения validator используйте совпадение аргументов длявызываемый элемент как текущая настройка не будет совпадать, потому что при выполнении теста они будут сравнивать разные экземпляры.

Mockito.doNothing().when(validator).validateData(any(List<OfferDetails>.class));

Вы вручную высмеиваете другие зависимости внутри метода теста, поэтому они не нужны вне этого

Тест теперь становится

public class IntegratorClassTest{
    @InjectMocks
    IntegratorClass integratorClass;

    @Mock
    Validator validator;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getCmsOffersTest()throws Exception{
        //Arrange
        ContentService contentService = Mockito.mock(ContentService.class);
        RequestClass requestClass = Mockito.mock(RequestClass.class);
        ContentList contentResponse = getContentList();
        Mockito.when(contentService.getContentCollection()).thenReturn(contentResponse);

        Mockito.doNothing().when(validator).validateData(any(List<OfferDetails>.class));

        //Act
        List<OfferDetails> offerListResult = integratorClass.getCmsOffers(contentService, requestClass);

        //Assert
        assertTrue(offerListResult.size() > 0);
    }
}
...