如何使用RestTemplate脱机进行单元测试? [英] How to unittest a class using RestTemplate offline?

查看:626
本文介绍了如何使用RestTemplate脱机进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个直接依赖于RestTemplate的类。我希望我有离线的JUnit测试。

I have a class which has direct dependency on the RestTemplate. I wish I have a JUnit test of it, offline.

我如何在我的unittest中模拟RestTemplate?

How could I mock a RestTemplate in my unittest?

推荐答案

我建议重构您的客户端代码,以删除的直接依赖RestTemplate ,并将其替换为对 RestOperations 的引用,这是 RestTemplate 实现的接口。你应该编码的那个。

I suggest refactoring your client code to remove the direct dependency on RestTemplate, and replace it with references to RestOperations, which is the interface implemented by RestTemplate. and the one you should be coding to.

然后你可以在你的代码中注入一个 RestOperations 的存根或模拟用于单元测试,并在实际使用时注入 RestTemplate

You can then inject a stub or mock of RestOperations into your code for unit testing, and inject a RestTemplate when using it for real.

这篇关于如何使用RestTemplate脱机进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆