Note that there are some explanatory texts on larger screens.

plurals
  1. POBest approach for breaking dependencies in C#?
    primarykey
    data
    text
    <p>We are looking at adding unit tests to our C# code base. I am finding it easy to add unit tests to simple classes, but classes that interact with other dependencies are more difficult. I have been looking at mocking frameworks, but was wondering about the best approach to write classes in the first place to break external dependencies, like file system, database and messaging system dependencies.</p> <p>To give an example, a routine listens on a socket for a message in a certain format - say MessageA. This is decoded, some calculations are done, this is re-encoded into a different binary format and the resulting message then sent, MessageB.</p> <p>My current testing approach is as follows. I extract an interface for all socket interactions, and create a mock interface. I set the interface in a singleton. Then run the class against hard coded inputs. The class under test will use the interface in the singleton to send/receive.</p> <p>I do a similar thing to test database interactions.</p> <p>This does not seem like the most flexible approach, how would you go about improving this to make it easier to test? If a mocking framework is the answer, how would I design the classes?</p> <p>Example code :</p> <pre><code>[SetUp] public void init() { // set message interface in singleton as mock interface CommAdapter.Instance.MessageAdapter = new MockMessage(); // build reference message from hard coded test variables initialiseMessageA(); // set input from mock message socket ((MockMessage) CommAdapter.Instance.MessageAdapter).MessageIn = m_messageA; } [Test] public void test_listenMessage_validOutput() { // initialise test class MessageSocket tS = new MessageSocket(); // read from socket tS.listenMessage(); // extract mock interface from singleton MockMessage mm = ((MockMessage) CommAdapter.Instance.MessageAdapter); // assert sent message is in correct / correstpoinding format Assert.AreEqual(1000001, mm.SentMessageB.TestField); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload