dev-notes/.NET/C#/Unit Testing.md
2021-04-24 13:26:22 +02:00

1.7 KiB

Unit Testing

MSTest

Microsoft Unit Testing Tutorial

To test a project add a MSTest Test Projet to the solution.

The test runner will execute any methods marked with [TestInitialize] once for every test the class contains, and will do so before running the actual test method itself.
The [TestMethod] attribute tells the test runner which methods represent tests.

In TestClass.cs:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Project.Tests
{
    [TestClass]
    public class TestClass
    {
        [TestMethod]
        public void TestMethod()
        {
            Assert.AreEqual(expected, actual);
            Assert.IsTrue(bool);
            Assert.IsFalse(bool);
            Assert.IsNotNull(nullable);

            // assertions on collections
            CollectionAssert.AreEqual(expexcted, actual),
        }
    }
}

UnitTest Overloaded Methods Naming standards for unit tests

xUnit

using System;
using Xunit;

namespace Project.Tests
{
    public class ClassTest
    {
        [Fact]
        public void TestMethod()
        {
            Assert.Equal(expected, actual);  // works on collections
            Assert.True(bool);
            Assert.False(bool);
            Assert.NotNull(nullable);

            // Verifies that all items in the collection pass when executed against action
            Assert.All<T>(IEnumerable<T> collection, Action<T> action);
        }
    }
}