TDD IN .NET: AN OVERVIEW OF RED, GREEN, REFACTOR

Test-driven development (TDD) is an advanced technique of using automated unit tests to drive the design of software and force decoupling of dependencies. The result of using this practice is a comprehensive suite of unit tests that can be run at any time to provide feedback that the software is still working.  It is a style of programming in which three activities are tightly interwoven: coding, testing (in the form of writing unit tests) and design (in the form of refactoring). In this article, we will focus .NET framework to explore the realm of TDD. Let us first delve into unit testing in .NET.

HOW TO START UNIT TESTING IN .NET

The first tool we need to start unit testing is a testing framework. From Microsoft Visual Studio 2008 Professional or above, Microsoft unit testing framework is built-in. We have a couple of open source frameworks too: NUnit and xUnit.

Before we start writing our tests, we need to decide what public method we want to test, what is the specific scenario and the expected result for that scenario. We may follow the following convention for our test.

public void Method_Scenario_Expectation

Next we will add the content of the test. A test contains three parts.

  • Arrange – setup for the test
  • Act – the actual invocation of the method
  • Assert – verification of pass/fail condition for the test

We should make sure that we use Assert functions to specify pass/failure functionality. We should verify for method calls as well, otherwise, the test will appear to have passed.

WRITING TESTS IN NUNIT 3.0

TEST ATTRIBUTE

The Test Attribute is one way of marking a method inside a TestFixture class as a test.

TESTCASE ATTRIBUTE

TestCase Attribute serves the dual purpose of marking a method with parameters as a test method and providing inline data to be used when invoking that method. Here is an example of a test being run three times, with three different sets of data:

[TestCase(12,4,3)]
[TestCase(7,6,6)]
[TestCase(19,5,2)]
public void DivideTest(int n, int d, int q) 
{   
   Assert.AreEqual(q, n / d); 
}
REPEAT ATTRIBUTE

Repeat attribute is used on a test method to specify that it should be executed multiple times. If any repetition fails, the remaining ones are not run and a failure is reported.

TIMEOUT ATTRIBUTE

The Timeout Attribute is used to specify a timeout value in milliseconds for a test case. If the test case runs longer than the time specified it is immediately cancelled and reported as a failure, with a message indicating that the timeout was exceeded.

ASSERTIONS

In NUnit 3.0, assertions are written primarily using the Assert.That method, which takes constraint objects as an argument.

Assert.AreEqual(4, 2+2);
Assert.That(2+2, Is.EqualTo(4));
ASSERTIONHELPER

Some users prefer a shorter form of assertion than is given by Assert.That. If you derive your test fixture class from AssertionHelper, the Expect() method may be used instead.

Expect(bool condition, string message, params object[] parms);
Expect(actual, EqualTo("Hello"));

LET’S CODE FOR OUR FIRST TEST

In order to make it easy, let’s start by testing a component I am working on.

  1. We will be using Microsoft Visual Studio 2015 with NUnit framework for unit tests in .NET. First of all, we need to install NUnit Test Adapter from Extensions and Updates section in Microsoft Visual Studio.
  2. In our test project, we will create a test class, called after our class-under-test. For example, if our class is called TaskController, test class will be called CreateTaskTests, TaskLinkTests and so on.
  3. We need to add reference of the class-under-test to our test class.
  4. We will write an unit test to cover a specific scenario of our application’s functionality or to cover for a bug fix.
  5. We will see the test fails.
  6. We will write the production code and will see the test now pass.
  7. Finally, we will refactor the code to increase clarity and remove duplication.

SKILL LEVELS

BEGINNER
  1. Being able to write a unit test prior to write the corresponding code.
  2. Being able to make a code sufficient to make a failing test pass.
INTERMEDIATE
  1. Practicing “test driven bug fixing” when a defect is found, writes a test exposing the defect before correction.
  2. Being able to decompose a compound program feature into a sequence of several unit tests to be written.
  3. Knowing and being able to name a number of tactics to guide the writing of tests.
EXPECTED BENEFITS
  1. Many teams report significant reductions in defect rates, at the cost of moderate increase in initial development effort.
  2. The same teams tend to report that these overheads are more than offset by a reduction in efforts in project’s final phases.
  3. Developers’ can have the peace of mind knowing that defect scenario is well covered by their code when they start working on application enhancements, new features etc.
  4. Veteran practitioners report that TDD leads to improved design qualities in the code, for instance improving the metrics of cohesion and coupling.

TDD can improve productivity by minimizing time spent in debugging, reduces the need for manual checking by developers and testers, helps developers maintain focus. TDD is highly recommended if we want to improve confidence in our code and create a living, up-to-date specification. 

Sr. SDET M Mehedi Zaman

Currently working as Sr. SDET at Robi Axiata Limited, a subsidiary of Axiata Group. As a Senior SDET: - Played a key role in introducing Agile Scrum methodology and implementing CI/CD pipeline to ensure quality & timely delivery. - Trained colleagues on emerging technologies, e.g. Apache Spark, Big Data, Hadoop, Internet of Things, Cloud Computing, AR, Video Streaming Services Technology, Blockchain, Data Science- Developed a test automation framework for Android and iOS apps - Developed an e2e web automation framework with Pytest - Performed penetration testing of enterprise solutions to ensure security and high availability using Kali, Burp Suite etc. - Learned Gauntlet security testing automation framework and shared the lesson learned in a knowledge sharing session

Leave a Reply

Your email address will not be published. Required fields are marked *