user000
9/17/2018 - 3:06 PM

Test with private field

Test with private field and RestTemplate exchange

package ru.rtl.gosweb.search.engine.services.impl;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.internal.util.reflection.FieldSetter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import ru.rtl.gosweb.search.engine.controllers.exceptions.CmsBlackListException;

import java.util.Arrays;
import java.util.List;

@RunWith(SpringRunner.class)
class CmsBlackQueryListImplTest {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private CmsBlackQueryListImpl cmsBlackQueryList;

    @BeforeEach
    public void setUp() throws NoSuchFieldException {
        MockitoAnnotations.initMocks(this);
        FieldSetter.setField(cmsBlackQueryList, cmsBlackQueryList.getClass().getDeclaredField("restTemplate"), restTemplate);
    }

    @Test()
    void checkQueryWhereWordInBlackList() {
        String badWord = "xxx";
        ResponseEntity<List<String>> response = new ResponseEntity<>(Arrays.asList("xxx", "yyy", "zzz"), HttpStatus.OK);
        Mockito.when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.any(HttpMethod.class),
                ArgumentMatchers.any(),
                ArgumentMatchers.<ParameterizedTypeReference<List<String>>>any())
        ).thenReturn(response);

        Assertions.assertThrows(CmsBlackListException.class, () -> cmsBlackQueryList.checkQuery(badWord));
    }
}