[英]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: 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");检查行时 Mockito.doReturn(byeArray).when(classA).method("url"); i notice that the object classA contains the rest template but it is null.我注意到 object classA 包含 rest 模板,但它是 null。
Mocking is done on dependencies, not on the class under test. Mocking 是在依赖项上完成的,而不是在被测的 class 上完成的。 there are ways to mock on the class under test methods also, that can be done using Spy
.还有一些方法可以在测试方法下模拟 class ,这可以使用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
. Class 被测ClassA
应使用@InjectMocks
注释,依赖项应使用@Mock
模拟。
Another thing to note, in your test case, you should call ClassA
method which needs to be tested.另外需要注意的是,在您的测试用例中,您应该调用需要测试的ClassA
方法。
@Test
public void test1() {
Mockito.doReturn(byeArray).when(restTemplate).doSomething(url);
classa.method(url);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.