为网络相关类编写单元测试

发布于 2024-07-26 05:01:46 字数 112 浏览 5 评论 0原文

我有一个负责网络通信的类。 我想对其进行单元测试。

为了为其编写测试,我陷入了困境,我必须实现一个与之通信的服务器,但这又需要它自己的测试。

如何为这样的类编写测试?

I have a class that is responsible for network communication. I would like to have a unit test for it.

Here is where I'm stuck in order to write a test for it i have to implement a server to communicate with but that in turn will require its own test.

How do you write tests for a class such as this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

划一舟意中人 2024-08-02 05:01:46

除非您正在编写低级驱动程序,否则您的类无疑依赖于其他类来进行实际通信。 在这种情况下,我将使用依赖项注入来提供这些类或它们周围的包装器(如果它们不容易被模拟)。 在您的测试中,您将提供您所依赖的类的模拟版本(如果您无法模拟实际的类,则提供包装器)。 验证您提供的模拟上的方法是否调用了具有正确参数的正确方法。 确保您有足够的单元测试来满足自己,您已经涵盖了真实依赖项的全部行为。 这对于您的单元测试来说就足够了。

您还需要一些集成测试。 不幸的是,最简单的方法可能是开发一个完整的模拟服务器来进行通信。 请注意,您的模拟服务器只需要实现接口,而不是另一端的实际代码。 提供一些额外的方法来允许您为集成测试设置服务器,以便模拟服务器发生预期的行为。

Unless you are writing low level drivers, your class undoubtedly depends on other classes to do the actual communications. In that event, I would use dependency injection to supply those classes or wrappers around them, if they aren't easily mocked. In you tests, you'd supply a mock version of the classes you are depending on (or the wrappers if you can't mock the actual classes). Verify that the correct methods with the proper parameters are invoked by your methods on the mocks that you supply. Make sure you have enough unit tests to satisfy yourself that you've covered the full range of behavior from the real dependencies. This will suffice for your unit tests.

You will also need some integrations tests. Unfortunately, the easiest way to do this is probably to develop a full-up mock server to communicate with. Note that your mock server need only implement the interface -- not the actual code on the other end. Supply some extra methods to allow you to set the server up for your integration tests so that the expected behavior with the mock server occurs.

会傲 2024-08-02 05:01:46

如果您单元测试负责网络通信的类,那么您测试您是否正确进行通信。 因此,提供一个模拟(如虚拟)服务器以供其通信。 您可以使用许多模拟库,例如 EasyMock 和 jMockit。 如果您想测试与实际服务器的实际通信,那么这就是集成测试。 当然,单元测试的确切定义因开发人员而异。

If you're unit-testing a class that's responsible for network communication, then you only test that you're doing the communication correctly. So supply a mock (as in, a dummy) server for it to communicate with. There are many mock libraries that you can use such as EasyMock and jMockit. If you want to test an actual communication with an actual server, then that's integration-testing. Of course, the exact definition of what unit-testing encompasses varies from developer to developer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文