RestTemplate的单元测试模拟
问题描述:
我有一个restTemplate的服务方法。作为单元测试的一部分,我试图嘲笑它,但一些失败。RestTemplate的单元测试模拟
服务方法:
@Autowired
private RestTemplate getRestTemplate;
return getRestTemplate.getForObject(restDiagnosisGetUrl, SfdcCustomerResponseType.class);
测试方法:
private CaresToSfdcResponseConverter caresToSfdcResponseConverter;
@Before
public void setUp() throws Exception {
caresToSfdcResponseConverter = new CaresToSfdcResponseConverter();
}
@Test
public void testConvert(){
RestTemplate mock = Mockito.mock(RestTemplate.class);
Mockito.when(mock.getForObject(Matchers.anyString(), Matchers.eq(SfdcCustomerResponseType.class))).thenReturn(sfdcCustomerResponseType);
}
sfdcRequest = caresToSfdcResponseConverter.convert(responseForSfdcAndHybris);
这是给NullPointerException异常。看起来它是无法模拟休息模板,它正在休息模板为空。任何帮助将不胜感激。谢谢
答
这不是无法嘲笑其余模板,但它不会将嘲笑休息模板注入您的生产类。至少有两种方法可以解决这个问题。
您可以更改您的生产代码和use constructor injection。移动RestTemplate给构造函数作为参数,那么你可以通过模拟测试:
@Service
public class MyService {
@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}
在您的测试,你会简单地创建服务为任何其他对象,并通过它你嘲笑休息模板。
或者你可以改变你的测试使用下面的注释注入您的服务:
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@InjectMocks
private MyService myService;
@Mock
private RestTemplate restTemplate;
@Test
public void testConvert(){
Mockito.when(mock.getForObject(Matchers.anyString(), Matchers.eq(SfdcCustomerResponseType.class))).thenReturn(sfdcCustomerResponseType);
}
}
你可以看到在另一个SO问题的例子:Using @Mock and @InjectMocks
我一般喜欢构造函数注入。
谢谢@ sm4。这完美的工作。我已经尝试过这种注入模拟的方式,但不知何故,它不工作。所以通过在谷歌中进行一些搜索来改变其他。再次感谢。 – arjun