.NET/C#
  • ASP.NET Core Overview
  • ASP.NET Core API tutorial
    • How to create ASP.NET Core C# API tutorial
      • launchSettings
      • Install swagger
        • Swagger best practices
      • Run the app
      • Fix CORS problem
      • Add AutoMapper
      • Add JWT reference
      • Add .gitignore
      • Basic structure & EF Core
      • AddSingleton
    • Loading Related Entities
  • Unit test controller logic in ASP.NET Core
    • Unit testing controllers
  • .NET Q&A
    • dotnet try
    • LINQ
      • LINQ Query Syntax
      • Lambda Expression
      • Standard Query Operators
  • .NET C# Interview questions
    • C# - .NET interview questions and answers [Part 1]
    • C# - .NET interview questions and answers [Part 2]
    • C# Interview questions [Part 3] General questions
  • C#
    • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • Project architecture
    • C# Advanced review
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Ref vs Out
      • Task
        • TaskFactory Class
  • MySQL
    • MySQL Lerning
      • SELECT
      • ORDER BY
      • WHERE
      • DISTINCT
      • IN
      • BETWEEN
      • Join
      • INNER JOIN
      • LEFT JOIN
      • RIGHT JOIN
      • GROUP BY
      • Subquery
      • UNION
    • Stored Procedures
      • CREATE PROCEDURE
  • Versioning API, MongoDB and ci-cd
    • Create a web API with ASP.NET Core and MongoDB
    • REST API versioning with ASP.NET Core
    • Design a CI/CD pipeline using Azure DevOps
      • Create a CI/CD pipeline for GitHub repo using Azure DevOps Starter
  • TFS & TFCV
    • What is Team Foundation Version Control
      • Develop and share your code in TFVC using Visual Studio
      • Suspend your work and manage your shelvesets
    • Newtonsoft Json.NET
      • Serializing and Deserializing JSON
  • MS-SQL
    • Quick tutorial
      • Add new column to a table
      • LEFT/RIGHT Reverse operator
      • Dates (Transact-SQL)
      • CAST and CONVERT (Transact-SQL)
      • Types of JOIN
      • Our first Left Outer Join
      • CROSS JOIN
Powered by GitBook
On this page
  • Unit testing controllers
  • Testing built packages locally with moq
  • Walkthrough: Create and run unit tests for managed code

Was this helpful?

  1. Unit test controller logic in ASP.NET Core

Unit testing controllers

PreviousLoading Related EntitiesNextdotnet try

Last updated 4 years ago

Was this helpful?

Unit testing controllers

Set up unit tests of controller actions to focus on the controller's behavior. A controller unit test avoids scenarios such as , , and . Tests that cover the interactions among components that collectively respond to a request are handled by integration tests. For more information on integration tests, see .

If you're writing custom filters and routes, unit test them in isolation, not as part of tests on a particular controller action. To demonstrate controller unit tests, review the following controller in the sample app.

Testing built packages locally with moq

You can either build from command line or explicitly Pack (from the context menu) the Moq.Package project.

Packages are generated in the bin folder in the repository root. To test these packages you can just add a package source pointing to it. You can also just place a NuGet.Config like the following anywhere above the directory with the test solution(s):

<configuration>
	<packageSources>
		<add key="moq" value="[cloned repo dir]\bin" />
  </packageSources>
</configuration>

Walkthrough: Create and run unit tests for managed code

using System;

namespace BankAccountNS
{
    /// <summary>
    /// Bank account demo class.
    /// </summary>
    public class BankAccount
    {
        private readonly string m_customerName;
        private double m_balance;

        private BankAccount() { }

        public BankAccount(string customerName, double balance)
        {
            m_customerName = customerName;
            m_balance = balance;
        }

        public string CustomerName
        {
            get { return m_customerName; }
        }

        public double Balance
        {
            get { return m_balance; }
        }

        public void Debit(double amount)
        {
            if (amount > m_balance)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            if (amount < 0)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            m_balance += amount; // intentionally incorrect code
        }

        public void Credit(double amount)
        {
            if (amount < 0)
            {
                throw new ArgumentOutOfRangeException("amount");
            }

            m_balance += amount;
        }

        public static void Main()
        {
            BankAccount ba = new BankAccount("Mr. Bryan Walton", 11.99);

            ba.Credit(5.77);
            ba.Debit(11.22);
            Console.WriteLine("Current balance is ${0}", ba.Balance);
        }
    }
}

Create a unit test project

  • On the File menu, select Add > New Project.

  • Type unit test in the search box, select C# as the language, and then select the C# Unit Test Project for .NET Core template, and then click Next.

  • Name the project BankTests and click Next.

  • Choose either the recommended target framework (.NET Core 3.1) or .NET 5, and then choose Create. The BankTests project is added to the Bank solution.

  • In the BankTests project, add a reference to the Bank project. In Solution Explorer, select Dependencies under the BankTests project and then choose Add Reference from the right-click menu.

  • In the Reference Manager dialog box, expand Projects, select Solution, and then check the Bank item.

  • Choose OK.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BankTests
{
    [TestClass]
    public class BankAccountTests
    {
        [TestMethod]
        public void TestMethod1()
        {
        }
    }
}

To keep reading more about simple test environment in c# please take a look

filters
routing
model binding
Integration tests in ASP.NET Core
here