java - 使用参数化引用类型参数模拟 Spring RestTemplate.exchange 调用

标签 java spring unit-testing mockito

我试图模拟对 RestTemplate.exchange() 的调用,但无法让它工作。目前对 Exchange() 的调用挂起,因此我相信正在调用实际的方法而不是我的模拟方法。对exchange()的调用如下:

ResponseEntity<List<MyType>> response = 
    restTemplate.exchange(queryStr, 
                   HttpMethod.GET, 
                   null,
                   new ParameterizedTypeReference<List<MyType>>() {
                   });

模拟如下:

@MockBean
private RestTemplate restTemplate;

@Test
public void testMethod() throws Exception {

    when(restTemplate.exchange(anyString(),
                eq(HttpMethod.GET),
                eq(null),
                eq(new ParameterizedTypeReference<List<MyType>>(){})
    )).thenReturn(new ResponseEntity<List<MyType>>(HttpStatus.OK));

    // rest of test code follows.

}

我尝试更改参数匹配器,以便它们匹配更广泛的参数类型(即,any() 代替 anyString()),但我得到相同的行为或错误“对交换的引用在方法交换(...)和方法交换(...)匹配方面都不明确”。我还收到“找不到适合 thenReturn(...) 的方法与 thenReturn(...) 不兼容”以及第一个错误。

提前致谢。

最佳答案

发现我们没有使用 Controller 中使用的 @Autowired 注解 RestTemplate 实例。

@RestController
public class myController {

    ...

    @Autowired  // <-- Forgot this annotation.
    private RestTemplate restTemplate;

    ...

}

现在模拟可以正常工作了。

关于java - 使用参数化引用类型参数模拟 Spring RestTemplate.exchange 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428337/

相关文章:

java - 为什么在尝试运行 Swing 桌面应用程序时会收到 HelpSetException - NoClassDefFoundError?

java - 如何提取具有 ID 但没有子值的子元素的值?

Java Applet 电子邮件问题

android - 如何为 Android/Gradle 设置单元测试

java - Tomcat java.lang.NoClassDefFoundError : Could not initialize class

java - 无法使用 Spring Security 保护 AngularJS 页面

mysql - Spring使用Windows用户而不是给定的用户名 'root'来访问mysql

java - FF4J在spring项目中使用AOP注解@Flip时不会翻转

ios - 在单元测试中使用 xcappdata 文件

c# - 使用 AutoFixture/AutoMoq 为深度嵌套的类创建模拟?