我有一个调用第三方 Web 服务的 Web 服务。
现在我想对我的 Web 服务进行单元测试。为此,我应该模拟第三方 Web 服务还是在测试期间调用它?
有没有关于单元测试的标准文档?
我有一个调用第三方 Web 服务的 Web 服务。
现在我想对我的 Web 服务进行单元测试。为此,我应该模拟第三方 Web 服务还是在测试期间调用它?
有没有关于单元测试的标准文档?
是的,您应该模拟第三方 Web 服务进行单元测试。以下是一些优点:
您的单元测试独立于其他组件,实际上只测试单元而不测试 Web 服务。如果您在单元测试中包含该服务并且它们失败了,您将不知道问题出在您的代码中还是在外部 Web 服务中。
您的测试独立于环境。如果 Internet 连接中断,或者您想在根本无法访问 Internet 的机器上进行测试,您的测试仍然有效。
如果不实际连接到 Web 服务,您的测试会快得多。 这可能看起来不是一件大事,但如果你有很多测试(你应该这样做),它真的很烦人。
您还可以通过模拟发送意想不到的东西来测试您的单元的稳健性。这在现实世界中总是会发生,如果真的发生了,您的 Web 服务应该会做出良好的反应,而不仅仅是崩溃。使用真正的 Web 服务时,无法对其进行测试。
但是,也有集成测试。在那里,您测试完整的设置,将所有组件放在一起(集成)。这是您将使用真正的 Web 服务而不是模拟的地方。
Both kinds of testing are important, but unit testing is typically done earlier and more frequently. It can (and should) be done before all components of the system are created. Integration testing requires a minimal amount of progress in all of most of the components.
这取决于您要进行的单元测试。
因此,如果您正在测试是否可以成功与第三方 Web 服务通信,您显然不会尝试模拟这一点。但是,如果您正在对属于您的 Web 服务产品的一些业务用例进行单元测试(与其他模块/Web 服务正在做的事情无关),那么您可能想要模拟第三方 Web 服务。
You should test both but both test cases does not fall under Unit testing.
Unit testing is primarily used for testing individual smaller pieces i.e. classes and methods. Unit testing is something that should preferably happen during the build process without any human intervention. So as part of Unit testing you should mock out the third party webservice. The advantage of mocking is that you can make the mocked object behave in many possible ways and test your classes/methods to make sure they handle all possible cases.
When multiple systems are involved, the test case falls under System/Integration/Functional testing. So as part of your System/Integration/Functional testing, you should call the methods in other webservice from your webservice and make sure everything works as expected.
Mocking is an usually essential in unit testing components which have dependent components. This is so because in unit testing , you are limited to testing that your code works correctly ( does what its contract says it will do ). If this method , in trying to do the part of its contract depends upon other component doing their part correctly , it is perfectly fine to mock that part out ( assuming that they work correctly ).
If you dont mock the other dependent parts , you soon run into problems. First , you cannot be certain what behavior is exhibited by that component. Second , you cannot predict the results of your own test ( because you dont know what was the inputs supplied to your tests )