Saturday, 26 September 2020

Unit Testing in C#

What is Test-Driven Development (TDD)?

Test-Driven Development (TDD) is a software development process in which tests are written before the actual code. The cycle typically involves:

  1. Writing a failing test for a new feature.
  2. Writing the minimum amount of code necessary to pass the test.
  3. Refactoring the code while keeping the tests passing.

This approach helps ensure that the code meets its requirements and is maintainable. 

What do you mean by a Unit test ?

In the software development process Unit Tests basically test individual parts of code (mostly methods) and make it work as expected by programmer. A Unit Test is a code written by any programmer which test small pieces of functionality of big programs.

Why do we need Unit test?

One of the most valuable benefits of using Unit Tests for your development is that it may give you positive confidence that your code will work as you have expected it to work in your development process. 

One of the fundamental principles of adopting unit testing is to follow a TDD (Test Driven Development) aproach where we have to write tests case first, and then write the simple code that will make the test pass.

We can use MS Unit tests, nUnit for creating Test methods. Below is an example of MS Unit test code.

Code to be tested

public class BasicMaths {  
    public double Add(double num1double num2) {  
        return num1 + num2;  
    }   

Test method for above code testing

[TestClass]  
public class UnitTest1 {  
    [TestMethod]  
    public void Test_AddMethod() {  
            BasicMaths bm = new BasicMaths();  
            double res = bm.Add(1010);  
            Assert.AreEqual(res20);  
        }  
}  

What are some common assertions used in unit tests?

Common assertions include:

  • Assert.AreEqual(expected, actual): Checks if two values are equal.
  • Assert.IsTrue(condition): Checks if a condition is true.
  • Assert.IsFalse(condition): Checks if a condition is false.
  • Assert.IsNull(object): Checks if an object is null.
  • Assert.IsNotNull(object): Checks if an object is not null.

How do you handle exceptions in unit tests?

You can handle exceptions in unit tests using the Assert.Throws method in NUnit or Assert.Throws<T> in xUnit. This checks if the expected exception is thrown during the execution of the code.

  [Test]
  public void Divide_ByZero_ThrowsException()
  {
      var calculator = new Calculator();
      Assert.Throws<DivideByZeroException>(() => calculator.Divide(5, 0));
  }

How can you improve the performance of unit tests?

To improve the performance of unit tests:

  • Minimize dependencies by mocking external resources.
  • Use parallel test execution where supported by the testing framework.
  • Avoid heavy initialization code in test setups.
  • Focus on testing only relevant parts of the application to reduce test complexity.
What is the Arrange-Act-Assert pattern, and how is it used in unit testing?
The Arrange-Act-Assert (AAA) pattern is a commonly used pattern in unit testing to structure test code. It involves three steps:

Arrange: In this step, the test environment is set up, including creating necessary objects, initializing variables, and mocking dependencies.
Act: In this step, the actual behavior being tested is executed. This typically involves calling a method or function with specific inputs.
Assert: In this step, the output of the behavior being tested is checked to ensure it meets the expected criteria. This can include checking return values, throwing expected exceptions, or verifying side effects.

By following the AAA pattern, unit tests become easier to read and understand, and it helps ensure that the tests are focused on one specific aspect of the code.

What is Mocking?

Mocking is a technique used in unit testing to simulate the behavior of external dependencies or objects that are difficult or impractical to use in a unit test. It involves creating mock objects that mimic the behavior of the real objects and can be controlled by the test code. Mock objects can be used to test the behavior of a unit of code in isolation, without the need for the real objects or dependencies. 

In short, mocking is creating objects that simulate the behavior of real objects.

Moq Framework

Moq is an open-source framework which can be found on GitHub. When start using Moq make sure you always install the very latest version.

When using Moq or any other mocking framework keep following restrictions in mind. You can not mock:

  1. Static class/methods.
  2. Extensions Methods.
  3. Non-virtual methods (except there is an interface).
How to Use Moq to Ease Unit Testing https://dzone.com/

What is code coverage, and why is it important in unit testing?
Code coverage is a critical metric in software testing that measures the percentage of code that has been executed by a test suite. It is important in unit testing because it helps to ensure that all parts of the code are being tested and that potential errors or bugs have been identified. By measuring code coverage, developers can identify areas of code that are not being tested and can adjust their test suite accordingly.




0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives