为什么要使用Mockito? [英] Why to use Mockito?

查看:144
本文介绍了为什么要使用Mockito?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Mockito的新手,我已经开始学习它.但是我有一些疑问.为什么我们需要使用Mockito?据我所知,它用于模拟(创建虚拟对象)并在具有实际运行代码之前编写测试用例.但是,如果我想测试已经实施的代码以检查它们是否正常运行,该怎么办.我该如何使用Mockito进行测试?

I am new to Mockito and I have started to learn it. But I have some questions. Why do we need to use Mockito? As far as I know it is used to Mock(Create dummy object) and write the test cases before having actual running code. But, what if I want to test my already implemented code to check whether they are functioning properly or not. How would I test it using Mockito?

例如,我有CRUD方法,我想通过使用我的Create方法在数据库中实际插入数据来测试Create是否正常运行,这与其他方法类似.我们可以使用Mockito实现它吗?如果没有,那么我是否需要在不使用Mockito的情况下为它们编写不同的测试用例?

For instance, I have CRUD methods and I would like to test whether Create is functioning properly by actually inserting data in database using my Create method, similarly for others. Can we attain it using Mockito. If not, then do I need to write different testcases for them without using Mockito?

推荐答案

该模拟用于您正在使用的每个类或服务. 正在测试的课程 不应被模拟.让我们假设您正在连接到由一个工程团队构建的远程服务,并且您不熟悉其内部功能,但是您知道它返回什么请求和响应. 在这种情况下,您可以创建该对象的模拟对象,并使用在不同情况下的响应返回集来定义该对象.每种情况都应进行自己不同的测试,对于每种响应,都应分别检查代码的响应(您正在研究).

The Mock is used to each class or service you are using. The class under test should not be Mocked. Lets assume you are connecting to a remote service which is being built by one of your engineering team, and you are not familiar with its internal functionality but you know what requests and response it returns. In that case, you can create a Mock of that Object, and defines it with set of responses returns in different situations. Each situation should get its own different test and for each response you should check separately the reaction of the code (you are working on).

另一个很好的例子是创建一个限制检查.让我们考虑一下在某些情况下可能引发的异常. 您可以模拟将抛出异常的对象,该异常很简单(如果使用Mock,则约为2-3行测试代码),并且可以检查编写的代码对该异常的反应.没有模拟,抛出异常可能是一件非常复杂的事情,如果您不熟悉这些小细节,那么使用起来就不那么容易.当然,Mock使您能够专注于要检查的主要功能,因为它使检查时间变得非常短.当上市时间很关键时,这是一种祝福.

Another great example is creating a limitation checks. Lets think of exception that might be thrown in some situations. You can Mock the object that will throw the Exception which is simple(~2-3 line of test code if you are using Mock) and you can check how the code you have written reacts to that Exception. Without the Mock the throwing of an exception might be really complicated thing and not so easy to use if you are not familiar with the small details. And of course the Mock enables you to be on focus of the main functionality you are checking cause it make the checking time very very small. And that is a bless when time to market is a critical thing.

这篇关于为什么要使用Mockito?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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