Source: HostForLIFE Blog

HostForLIFE Blog European ASP.NET Core 9.0 Hosting - HostForLIFE :: Unit Testing in .NET Core with xUnit

Unit testing is a key component of software testing that developers can handle on their own. It is used to test the smallest components of your code. As you write your code, you may use unit tests to make sure it is working as expected or yielding the desired outcomes. All developers benefit from testing the code before submitting it to source control. NUnit, xUnit, and other frameworks are among the many available for unit testing. We shall examine the unit testing procedure in this article.initiative for the Net Web API. Here, we are utilizing the xUnit framework, which is a free and open-source tool, to achieve the same goal. web development. Here, we'll start by addressing the most basic functions. Creating a Testing ProjectAt last, we reach the stage where our tests will require the creation of a new project. We will take advantage of the handy xUnit testing project template that comes with Visual Studio 2022 when we use it.An open-source unit testing tool for the.NET framework called xUnit makes testing easier and frees up more time to concentrate on creating tests: In order to inject the IEmployeeService interface into our controller during testing, we now need to construct our fictitious implementation of the interface. We are going to populate its in-memory collection with our fictitious data.public class EmployeeServiceFake : IEmployeeService{    public readonly Dictionary<Guid, Employee> _employees;    public EmployeeServiceFake()    {        _employees = new Dictionary<Guid, Employee>        {            {                new Guid("503df499-cabb-4699-8381-d76917365a9d"),                new Employee                {                    Id = new Guid("503df499-cabb-4699-8381-d76917365a9d"),                    Name = "Name1",                    Mno = "1234567890",                    Salary = 36000,                    Type = EmployeeType.Permanent                }            },            {                new Guid("77cf78a6-d6e8-4d50-afeb-39eae4567c62"),                new Employee                {                    Id = new Guid("77cf78a6-d6e8-4d50-afeb-39eae4567c62"),                    Name = "Name2",                    Mno = "1234567890",                    Salary = 24000,                    Type = EmployeeType.Temporary                }            }        };    }    public bool Exists(Guid id)    {        return _employees.ContainsKey(id);    }    public Guid Create(Employee employee)    {        _employees.Add(employee.Id, employee);        return employee.Id;    }    public void Delete(Guid id)    {        _employees.Remove(id);    }    public List<Employee> GetAll()    {        return _employees.Values.ToList();    }    public Employee GetById(Guid id)    {        if (!_employees.ContainsKey(id))        {            return null;        }        return _employees[id];    }    public Guid Update(Employee employee)    {        var emp = _employees[employee.Id];        emp.Mno = employee.Mno;        emp.Name = employee.Name;        emp.Type = employee.Type;        emp.Salary = employee.Salary;        _employees[employee.Id] = emp;        return employee.Id;    }}Write some unit tests, please! We are now prepared to write tests for our EmpController's first GetAll method.The xUnit framework uses the [Fact] attribute, which we will use to decorate test methods to identify them as the real testing methods. In the test class, in addition to the test methods, we can have an infinite number of helper methods.The AAA principle (Arrange, Act, and Assert) is typically followed when writing unit tests. Arrange: this is the part where you usually get everything ready for the test or put another way, you get the scene ready for the test (making the objects and arranging them as needed). Act: Here is where the procedure that we are testing is carried out. Assert: In this last section of the test, we contrast the actual outcome of the test method's execution with our expectations. Testing Our ActionsWe will want to confirm the following in the Get method, which is the first method we are testing. Whether the method yields the OkObjectResult, a response code of 200 for an HTTP request. Whether the returned object includes every item in our list of Emps. Testing the Get Methodpublic class EmployeeControllerTest{    private readonly EmployeeController _employeeController;    private readonly IEmployeeService _employeeService;    public EmployeeControllerTest()    {        _employeeService = new EmployeeServiceFake();        _employeeController = new EmployeeController(_employeeService);    }    [Fact]    public void Get_WhenCalled_ReturnsOkResult()    {        // Act        var response = _employeeController.GetAll();        // Assert        Assert.IsType<OkObjectResult>(response as OkObjectResult);    }    [Fact]    public void Get_WhenCalled_ReturnsAllItems()    {        // Act        var response = _employeeController.GetAll() as OkObjectResult;        // Assert        var result = Assert.IsType<List<Employee>>(response.Value);        Assert.Equal(2, result.Count);    }}The class we wish to test is the one in which we create an instance of the EmployeeController object. It's crucial to remember that this constructor is called before every test method, which implies that the test is always run on a new object and the controller state is always reset.This is crucial because, regardless of how often or in what order we run the tests, the test methods ought to be independent of one another and should yield consistent testing outcomes.Testing the GetById Method[Fact]public void GetById_FakeGuidPassed_ReturnsNotFound(){    // Arrange    var empId = Guid.NewGuid();    // Act    var response = _employeeController.GetById(empId);    // Assert    Assert.IsType<NotFoundResult>(response);}[Fact]public void GetById_ValidGuidPassed_ReturnsOk(){    // Arrange    var empId = new Guid("503df499-cabb-4699-8381-d76917365a9d");    // Act    var response = _employeeController.GetById(empId);    // Assert    Assert.IsType<OkObjectResult>(response);}[Fact]public void GetById_ValidGuidPassed_ReturnsEmp(){    // Arrange    var empId = new Guid("503df499-cabb-4699-8381-d76917365a9d");    // Act    var response = _employeeController.GetById(empId) as OkObjectResult;    // Assert    Asse

Read full article »
Est. Annual Revenue
$25-100M
Est. Employees
250-500
CEO Avatar

CEO

Anthony Johnson

CEO Approval Rating

70/100