Unit testing 客户机-服务器应用程序上的TDD
目前,我正在创建一个服务器应用程序来接收特定于协议的消息。我需要创建测试来确保我正确地实现了协议。这是某种集成测试吗?如果是肯定的,我可以使用单元测试工具进行集成测试吗?最后,创建此类测试的最佳方法是什么 如果你知道正确的回答是什么,那么我会这样做: 将负责处理协议逻辑的类与处理连接机制的代码分开 编写测试,一次一个,为给定的输入消息集指定正确的响应 实施这些行为 例如,如果hello消息应该用howdy消息响应,那么您的测试可能如下所示:Unit testing 客户机-服务器应用程序上的TDD,unit-testing,tdd,client-server,protocols,network-protocols,Unit Testing,Tdd,Client Server,Protocols,Network Protocols,目前,我正在创建一个服务器应用程序来接收特定于协议的消息。我需要创建测试来确保我正确地实现了协议。这是某种集成测试吗?如果是肯定的,我可以使用单元测试工具进行集成测试吗?最后,创建此类测试的最佳方法是什么 如果你知道正确的回答是什么,那么我会这样做: 将负责处理协议逻辑的类与处理连接机制的代码分开 编写测试,一次一个,为给定的输入消息集指定正确的响应 实施这些行为 例如,如果hello消息应该用howdy消息响应,那么您的测试可能如下所示: Mock<IProtocolOut> ou
Mock<IProtocolOut> outbound = new Mock<IProtocolOut>();
MyProtocolHandler handler = new MyProtocolHandler(outbound); // assuming that the handler takes the outbound receiver as a parameter.
outbound.Expect(o=>o.HowdyMessage()); // we expect to get a HowdyMessage back
handler.HelloMessage(); // 'fake' a HelloMessage into the handler
outbound.VerifyAll(); // assert that the 'howdy' message was sent.
Mock<IProtocolOut> outbound = new Mock<IProtocolOut>();
MyProtocolHandler handler = new MyProtocolHandler(outbound); // assuming that the handler takes the outbound receiver as a parameter.
handler.HelloMessage(); // fake the message being sent
outbound.AssertWasCalled(o=>o.HowdyMessage());
在这种情况下,mock所做的只是断言进行了某些调用。这也可以通过手动滚动类来进行验证——模拟并没有什么神奇之处,它们只是使这种验证更容易进行
如果您有一个支持Arrange/Act/Assert的模拟库,它看起来更像这样:
Mock<IProtocolOut> outbound = new Mock<IProtocolOut>();
MyProtocolHandler handler = new MyProtocolHandler(outbound); // assuming that the handler takes the outbound receiver as a parameter.
outbound.Expect(o=>o.HowdyMessage()); // we expect to get a HowdyMessage back
handler.HelloMessage(); // 'fake' a HelloMessage into the handler
outbound.VerifyAll(); // assert that the 'howdy' message was sent.
Mock<IProtocolOut> outbound = new Mock<IProtocolOut>();
MyProtocolHandler handler = new MyProtocolHandler(outbound); // assuming that the handler takes the outbound receiver as a parameter.
handler.HelloMessage(); // fake the message being sent
outbound.AssertWasCalled(o=>o.HowdyMessage());
当然,协议的接口不必是消息的强类型。你也可以做类似的事情:
Mock<IProtocolOut> outbound = new Mock<IProtocolOut>();
MyProtocolHandler handler = new MyProtocolHandler(outbound); // assuming that the handler takes the outbound receiver as a parameter.
handler..ReceiveMessage("hello"); // fake the message being sent
outbound.AssertWasCalled(o=>o.ReceiveMessage("howdy"));
编辑以澄清测试范围
所有这些都不需要“实际”连接。他们只测试处理协议的逻辑方面,并假定您在逻辑协议处理和连接管理之间存在分歧。TDD和集成测试不是一回事。如果您正在跨越流程边界,这在本例中很有可能,那么是的,这是一个集成测试,而不是单元测试。我发现了这个链接,它证实了您刚才所说的:这些测试与TDD单元测试非常独立,实际上是集成测试。。。尽管如此,它们仍然可以使用相同的测试框架来实现,比如xUnit。只要做你认为必要的测试。单位,TDD,集成,谁在乎。试一试,你能考虑回答吗?