问题
Currently I'm creating a server application to receive protocol-specific messages. I need to create tests to ensure that I've implemented the protocol correctly. Is this some kind of integration testing? If positive, can I make an integration testing with unit testing tools? And finally, what is the best way to create these kind of tests?
回答1:
If you know what the correct responses are, then here's what I'd do:
Separate the class responsible for the logic of handling the protocol from the code dealing with the mechanics of the connection.
Write tests, one at a time, specifying the correct response for a given set of input messages.
Implement those behaviors.
For instance, if a "hello" message is supposed to be responded to with a "howdy" message, your test might look something like this:
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.
All the mock does in this case is assert that certain calls were made. This can be done by hand-rolling classes to do the verification as well - there's nothing magic about mocks, they just make it easier to do this type of verification.
If you have a mock library that supports Arrange/Act/Assert, it'd look something more like this:
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());
The interfaces for the protocols don't have to be strongly typed with the messages, of course. You could also do something similar to this:
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"));
(edit for clarification of test scope)
None of these require an 'actual' connection. They test the logical aspects of handling the protocol only, and presume that you have a split between the logical protocol handling, and the connection management.
来源:https://stackoverflow.com/questions/2308679/tdd-on-client-server-application