Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing RestTemplate的单元测试模拟_Unit Testing_Junit_Mockito_Invocationtargetexception - Fatal编程技术网

Unit testing RestTemplate的单元测试模拟

Unit testing RestTemplate的单元测试模拟,unit-testing,junit,mockito,invocationtargetexception,Unit Testing,Junit,Mockito,Invocationtargetexception,我有一个使用restTemplate的服务方法。作为单元测试的一部分,我试图对它进行模拟,但有些测试失败了 服务方式: @Autowired private RestTemplate getRestTemplate; return getRestTemplate.getForObject(restDiagnosisGetUrl, SfdcCustomerResponseType.class); 试验方法: private CaresToSfdcResponseConverter caresT

我有一个使用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。看起来它无法模拟rest模板,并且由于rest模板为空,它正在中断。任何帮助都将不胜感激。谢谢

模拟rest模板不会失败,但不会将模拟的rest模板注入到生产类中。至少有两种方法可以解决这个问题

您可以更改生产代码和。将RestTemplate作为参数移动到构造函数中,然后您可以在测试中通过模拟:

@Service
public class MyService {
    @Autowired
    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}
在测试中,您只需将服务创建为任何其他对象,并将其传递给模拟rest模板

或者,您可以使用以下注释更改测试以注入服务:

@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问题中看到一个示例:


我通常更喜欢构造函数注入。

谢谢@sm4。这很有效。最初我尝试过这种注入mock的方法,但不知怎么的,它不起作用。所以通过谷歌的搜索改变了另一个。再次感谢。