简体   繁体   中英

How to mock RestTemplate in Java Spring boot?

I am trying to mock RestTemplate getEntity() method using below code but i am getting exception and i am new for Unit testing

can some one help me please what is my mistake

Class

public List<SampleObject1> getGitHubUSersList(){

        try {
            ResponseEntity<SampleObject1[]>responseEntity = restTemplate.getForEntity("https://api.github.com/users", SampleObject1[].class);
            List<SampleObject1>arrayList  = Arrays.asList(responseEntity.getBody());
            System.out.println("final list is---->"+objectMapperl.writeValueAsString(arrayList));
            return arrayList;
        }catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }

Test Class

public class SampleServiceTest1 {

    @Mock
    RestTemplate mockrestTemplate;

    @InjectMocks
    @Spy
    SampleService1 sampleService;

    @Before
    public void setup() {
    MockitoAnnotations.initMocks(this);
    }

@SuppressWarnings("unchecked")
@Test
public void getGitHubUSersListTest() {

    List<SampleObject1> sampleObject1s = new ArrayList<>();

    SampleObject1 sampoleObject1 = new SampleObject1();
    sampoleObject1.setId(1);
    sampoleObject1.setLogin("sample1");
    sampoleObject1.setNode_id("sample2");
    sampleObject1s.add(sampoleObject1);

    SampleObject1 sampoleObject2 = new SampleObject1();
    sampoleObject2.setId(2);
    sampoleObject2.setLogin("sample3");
    sampoleObject2.setNode_id("sample4");
    sampleObject1s.add(sampoleObject2);

    Mockito.doReturn(sampleObject1s).when(mockrestTemplate).getForEntity(Matchers.anyString(),  ArgumentMatchers.any(Class.class));

    List<SampleObject1> list = sampleService.getGitHubUSersList();

    assertNotNull(list);
}

}

Error

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
Also, if you use @Mock annotation don't miss initMocks()
    at com.example.microservice.service.SampleServiceTest1.getGitHubUSersListTest(SampleServiceTest1.java:50)

Your mock setup is wrong getForEntity does not return a List<SampleObject1> so you can not set that as return you need to return ResponseEntity<SampleObject1[]> .

So to solve your problem. Declare a new mock

@Mock
private ResponseEntity<SampleObject1[]> mockResponseEntity

doReturn(mockResponseEntity).when(mockrestTemplate).getForEntity(anyString(),  any(Class.class));
doReturn(new SampleObject1[]{sampoleObject1, sampoleObject2}).when(mockResponseEntity).getBody();

This should work.

I am assuming restTemplate response to be a List and not an Array.

@RunWith(MockitoJUnitRunner.class)
public class SampleServiceTest {

    @InjectMocks
    private SampleService sampleService;

    @Mock
    private RestTemplate restTemplate;

    @Test
    public void name() {
        List<Pair> restResponseList = Arrays.asList(Pair.with("K1","V1"),Pair.with("K2","V2"));

        when(restTemplate.getForEntity(any(String.class), Matchers.<Class<List>>any()))
                .thenReturn(new ResponseEntity<>(
                        restResponseList,
                        new HttpHeaders(),
                        HttpStatus.OK));

        List<Pair> testResponse =sampleService.getGitHubUSersList();
        assertEquals(Pair.with("K1","V1"),testResponse.get(0));
        assertEquals(Pair.with("K2","V2"),testResponse.get(1));
    }
}

I see two potential issues with the code above which I think need to be fixed for your test to run correctly:

  1. You need to apply @RunWith(MockitoJUnitRunner.class) to your class declaration line (ie public class SampleServiceTest1 { ).
  2. When using the @InjectMocks and @Spy annotations, you need to have an actual instance. As such, I would change your line SampleService1 sampleService; to something like SampleService1 sampleService = new SampleService1();

For examples on doing these two things, check out this helpful Baeldung article on Mockito annotations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM