Saturday 26 September 2020

Unit Testing in C#

 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 is Mocking?

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

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/

0 comments:

Post a Comment

Topics

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

Dotnet Guru Archives