We are considering adding unit tests to our C # code base. It's easy for me to add unit tests to simple classes, but classes that interact with other dependencies are harder. I looked at mocking frameworks, but wondered about the best approach to writing classes in the first place, to break external dependencies such as the file system, databases, and messaging systems.
To give an example, the procedure listens on a socket for a message in a specific format - say, MessageA. It is decoded, some calculations are done, it is transcoded into another binary format, and the resulting message is then sent to MessageB.
My current testing approach is as follows. I am extracting an interface for all socket interactions and am creating an interface layout. I installed the interface in singleton mode. Then run the class against hard-coded inputs. The class test will use the singleton interface to send / receive.
I am doing a similar thing for testing database interactions.
This doesn't seem like the most flexible approach, how would you improve this to make it easier to test? If a mocking framework is the answer, how would I design classes?
Code example:
[SetUp]
public void init()
{
CommAdapter.Instance.MessageAdapter = new MockMessage();
initialiseMessageA();
((MockMessage) CommAdapter.Instance.MessageAdapter).MessageIn = m_messageA;
}
[Test]
public void test_listenMessage_validOutput()
{
MessageSocket tS = new MessageSocket();
tS.listenMessage();
MockMessage mm = ((MockMessage) CommAdapter.Instance.MessageAdapter);
Assert.AreEqual(1000001, mm.SentMessageB.TestField);
}
source
share