Integration Testing in Dotnet With InMemory Db

Integration Testing in Dotnet With InMemory Db

Integration testing is a software testing technique, where individual units of a program are integrated together and tested as a group for interacting harmoniously with each other. It concerns the testing of interactions and interfaces between modules, components, or systems to see if they behave as expected once integrated.

📢 Always use real database for integration testing instead of InMemory Db.

Purpose

  • This is to ensure that various components or modules behave according to expectation.
  • In the case of integration, to find out whether there are problems concerning interfaces or inconsistencies in data.
  • Verifying whether it meets the set specifications and functionality of an integrated system.

Tech Used in this project

  • .Net 8 web APIs (controller)
  • Sqlite
  • EntityFrameworkCore
  • xUnit
  • In Memory Database (for testing)

Let’s get started

Create a sln file (I have named it PersonGithubActionsDemo) with two projects

[Read More]

Unit Testing in Dotnet Core With Nsubstitute

Unit Testing in Dotnet Core With Nsubstitute

As the name suggesting , Unit testing is a software testing where smallest units of the application such as methods are tested in the isolation, so that we can ensure our software is working as expected.

Commonly used testing frameworks

  • MSTest
  • nUnit
  • xUnit

Mocking frameworks

Mocking framework is a library which allows us to mock the objects. For example, a PeopleController is injected with the IPersonRepository. While testing the PeopleController, we need the IPersonRepository. Mock frameworks comes to rescue in that situation. With the help of mock frameworks we can mock the IPersonRepository and mimic it’s behavior. Some popular mocking libraries are:

[Read More]

Set Bearer Token to Each Request Automatically in Postman

Set Bearer Token to Each Request Automatically in Postman

When we work with postman to test the endpoints, and those endpoints are authorized, each time (until it expires) we need to pass the token in the authorization header. To get the token, we need to call the login or authentication API . This process feels quite irritating , because we programmers hates this manual working. We always want an easy and automatic workflow. Let’s see how can we achieve this with postman.

[Read More]

.Net Core API CRUD With PostgreSql

.Net Core API CRUD With PostgreSql

When we create an application with .NET, we tend to use the Microsoft tech stack like Visual Studio IDE, Microsoft SQL Server, Windows Operating System, and Azure. However, things have changed since the introduction of .NET Core. We are no longer bound to a specific operating system and database.

In this blog post, we will learn how to create a Web API CRUD (Create, Read, Update, Delete) application using .NET Core and a Postgres database.

[Read More]

Higher Order Functions in C#

Higher Order Functions in C#

Higher-order functions (HOF) are functions that can take a function as an argument or return a function or both. In C#, higher-order functions are achieved using delegates, lambda expressions and expression trees.

Example 1: Using a Delegate

// Declare a delegate that takes an int and returns an int
public delegate int IntOperation(int x);

public class Program
{
    // Higher-order function that takes a delegate as an argument
    public static int PerformOperation(int value, IntOperation operation)
    {
    return operation(value);
    }

    public static void Main()
    {
        // Create a delegate instance that points to the Square method
        IntOperation square = x => x \* x;

        // Pass the delegate to the higher-order function
        int result = PerformOperation(5, square);
        Console.WriteLine(result); // Output: 25
    }

}

Example 2 : Using lambda expression

// Higher-order function that takes a lambda expression as an argument
public static int PerformOperation(int value, Func<int, int\> operation)
{
 return operation(value);
}

// main method

// Define a lambda expression that squares a number
Func<int, int> square = x => x * x;

// Pass the lambda expression to the higher-order function
int result = PerformOperation(5, square);

Example 3: Function as a Return Value

public class Program
{
    // Higher-order function that returns a function
    public static Func<int, int\> GetOperation(bool isSquare)
    {
        if (isSquare)
        {
            return x => x \* x;
        }
        else
        {
            return x => x + x;
        }
    }

    public static void Main()
    {
        // Get a function that squares a number
        Func<int, int> operation = GetOperation(true);

        // Use the returned function
        int result = operation(5);
        Console.WriteLine(result); // Output: 25
    }
}

In c#, higher order functions are everywhere. If one have used LINQ, must have used HO functions. Collection’s Where() is the good example.

[Read More]

Let's dive into various types of properties in c#

Let's dive into various types of properties in c#

I assume you have some knowledge of C# properties. If not, here’s a quick definition: A property is a class member that provides a flexible way to read, write, or compute the value of a private field. Don’t worry if you’re new to properties; we’ll be using them in this blog, and I’ll explain them as we go along.

1. Properties with getter and setter

public class Person
{
 public string Name { get;set; }
 public int Age { get; set;}
}

Generally, we define properties like this. The Person class has two properties Name and Age, each with getters and setters. This enables you to set and read their values.

[Read More]

Understanding The Pure And Impure Functions in C#

Understanding The Pure And Impure Functions in C#

Pure functions

Pure function is that:

  1. Always returns the same output given the same inputs.
  2. Does not modify the state of object or any external state.
  3. Does not have any side effects such as I/O operations, exceptions or modifying external variables.
  • In other words, a pure function takes input, process it and returns the output without modifying anything else.
  • Pure functions are easy to test and debug.

Examples

  1. Mathematical calculations
public int Add(int a, int b)
{
 return a + b;
}
  1. String manipulation
public string Concatenate(string a, string b)
{
 return a + b;
}
  1. Array operations
public int[] SortArray(int[] array)
{
 return array.OrderBy(x => x).ToArray();
}
  1. Data transformations
public string ConvertToString(int value)
{
 return value.ToString();
}
  1. Validation
public bool IsValidEmail(string email)
{
 return email.Contains("@");
}

Impure Functions

Impure function is that

[Read More]

Command Pattern With C#

Command Pattern With C#

The Command Pattern is a behavioral design pattern that turns a request into a stand-alone object containing all the information about the request. This conversion allows you to parameterize methods with different requests, queue requests, and support undoable operations.

In simpler terms, the Command Pattern encapsulates a request as an object, thereby allowing users to decouple the sender (invoker) from the object that performs the action (receiver).

[Read More]

Adapter Pattern: Bridging the gap between incompatible interfaces

Adapter Pattern: Bridging the gap between incompatible interfaces

The Adapter pattern is a structural design pattern that allows two incompatible interfaces to work together by converting the interface of one class into an interface expected by the clients. In other words, it acts as a bridge between two incompatible interfaces, enabling them to communicate with each other.

Adapters in real world?

For a phone that does not support a 3.5 mm audio jack, you can use a USB-C to 3.5 mm audio adapter. The phone has only a USB-C port, so the adapter converts the USB-C connection into a 3.5 mm audio jack, allowing you to use traditional wired headphones with your phone. The adapter bridges the gap between the old headphone interface and the new phone design.

[Read More]

Facade Pattern With C#

Facade Pattern With C#

The Facade pattern is a structural design pattern that provides a simplified interface to a complex system of classes or interfaces.

Let’s understand it with example. Imagine a home automation system.

home automation system

Let’s implement it programmatically.

public class FacadePatternTestDrive
{
    public static void Main(string[] args)
    {
        ILights lights = new Lights();
        IAirConditioner airConditioner = new AirConditioner();
        ISecuritySystem securitySystem = new SecuritySystem();

        // When leaving home
        lights.TurnOff();
        airConditioner.TurnOff();
        securitySystem.Arm();
        Console.WriteLine("You have left home.");

        // When entering home
        lights.TurnOn();
        airConditioner.TurnOn();
        securitySystem.Disarm();
        Console.WriteLine("Welcome home!");
    }

}

Note: AirConditioner, SecuritySystem and Lights class is not present in the above example for the sake of simplicity. We will write those classes when we implement the facade pattern.

[Read More]