如何使用最小起订量模拟被测类的方法
我有一个服务类想要进行单元测试。该服务调用存储库类方法来保存一些数据。但在调用 save 方法之前,我有一个属于被测服务类的 validate 方法,该方法验证要作为存储库 save 方法的参数保存的类的属性。
我知道要验证是否调用了存储库保存方法,我必须模拟存储库类并设置保存方法,但是如何验证在对该方法进行单元测试时是否调用了属于被测服务类的验证方法因为他们属于同一类而正在测试?
I have a service class that i want to unit test. The service calls a repository class method in order to save some data. But before I call the save method, I have a validate method that belongs to the service class under test which validates the properies of the class to be persisted as a parameter to the repository save method.
I know that to verify that the repository save method is called, i have to mock the repository class and set up the save method, but how do i verify that the validate method belonging to the service class under test is called when unit testing the method under test since they belong to the same class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过传入使
Verify
方法报告错误的无效数据来间接测试这一点。示例:
Verify
对无效值引发异常:让单元测试检查是否引发了此异常Verify
返回false
以及被测方法不会调用Save
,因为:在存储库模拟上断言没有调用Save
。You test this indirectly by passing in invalid data that makes the
Verify
method to report an error.Examples:
Verify
throws an exception on an invalid value: Make your unit test check that this exception was thrownVerify
returnsfalse
and the method under test doesn't callSave
because of this: Assert on your repository mock that no call toSave
happened.除非您将服务类注入到其他类中,否则您不能这样做。这是您需要做的。
You can't untill you inject your service class in some other class. Here is what you need to do.