简体   繁体   中英

Mockito rest template is always null for mocked object

When mocking a class which contains a rest template, the rest template is always null, my code is:

public class ClassA {

    private final RestTemplate restTemplate;

    public ClassA(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public byte[] method(String url) {
       // do some restTemplate.getForObject()
    }
}

   @RunWith(SpringRunner.class)
   @SpringBootTest(classes = {Application.class})
public class TestClass {

    @Mock
    private ClassA classa

     public void test1() {

      Mockito.doReturn(byeArray).when(classA).method("url");
     }
}

When inspecting the line Mockito.doReturn(byeArray).when(classA).method("url"); i notice that the object classA contains the rest template but it is null.

Mocking is done on dependencies, not on the class under test. there are ways to mock on the class under test methods also, that can be done using Spy .

In your current case, it should be like this.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class TestClass {

    @InjectMock
    private ClassA classa

    @Mock
    private RestTemplate restTemplate

    @Test
    public void test1() {
      Mockito.doReturn(byeArray).when(restTemplate).method(url);
   }
}

Class under test ClassA should be annotated with @InjectMocks and dependencies should be mocked using @Mock .

Another thing to note, in your test case, you should call ClassA method which needs to be tested.

@Test
public void test1() {
  Mockito.doReturn(byeArray).when(restTemplate).doSomething(url);

  classa.method(url);
}

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