0
0
CsharpHow-ToBeginner · 4 min read

How to Write Unit Tests in C#: Simple Guide with Examples

To write a unit test in C#, use the [TestMethod] attribute on a method inside a class marked with [TestClass]. Use assertions like Assert.AreEqual() to check expected results. Run tests with a test runner such as MSTest in Visual Studio.
📐

Syntax

A unit test in C# is a method inside a class marked with [TestClass]. Each test method uses the [TestMethod] attribute. Inside the test method, you call the code to test and use Assert methods to check if the output matches the expected result.

  • [TestClass]: Marks the class as containing tests.
  • [TestMethod]: Marks the method as a test.
  • Assert: Provides methods to verify test results.
csharp
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyTests
{
    [TestClass]
    public class CalculatorTests
    {
        [TestMethod]
        public void Add_TwoNumbers_ReturnsSum()
        {
            // Arrange
            int a = 5;
            int b = 3;
            int expected = 8;

            // Act
            int actual = a + b;

            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}
💻

Example

This example shows a simple unit test for a Calculator class method Add. It checks if adding 2 and 3 returns 5.

csharp
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CalculatorApp.Tests
{
    public class Calculator
    {
        public int Add(int x, int y) => x + y;
    }

    [TestClass]
    public class CalculatorTests
    {
        [TestMethod]
        public void Add_WhenCalled_ReturnsSum()
        {
            // Arrange
            var calculator = new Calculator();
            int expected = 5;

            // Act
            int result = calculator.Add(2, 3);

            // Assert
            Assert.AreEqual(expected, result);
        }
    }
}
Output
Test Passed
⚠️

Common Pitfalls

Common mistakes when writing unit tests in C# include:

  • Not marking the test class with [TestClass] or test methods with [TestMethod], so tests are not discovered.
  • Testing multiple things in one test method instead of one clear behavior.
  • Not using assertions properly, which makes tests meaningless.
  • Writing tests that depend on external resources like databases, making them slow and flaky.
csharp
/* Wrong: Missing [TestMethod] attribute, test won't run */
[TestClass]
public class SampleTests
{
    public void TestWithoutAttribute()
    {
        Assert.IsTrue(true);
    }
}

/* Right: Properly marked test method */
[TestClass]
public class SampleTests
{
    [TestMethod]
    public void TestWithAttribute()
    {
        Assert.IsTrue(true);
    }
}
📊

Quick Reference

Here is a quick summary of key attributes and methods used in C# unit testing with MSTest:

Attribute/MethodPurpose
[TestClass]Marks a class that contains unit tests
[TestMethod]Marks a method as a unit test
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.ThrowsException(action)Checks if an exception of type T is thrown

Key Takeaways

Mark test classes with [TestClass] and test methods with [TestMethod] to enable test discovery.
Use Assert methods to verify your code behaves as expected.
Keep tests focused on one behavior and avoid external dependencies.
Run tests using Visual Studio Test Explorer or command line tools.
Write clear Arrange-Act-Assert steps for readable tests.