write unit test in csharp

To write a unit test in C#, follow the steps below:

  1. Create a new class library project in Visual Studio.

  2. Add a reference to the project that contains the code to test.

  3. Add a reference to the NUnit or MSTest framework.

  4. Create a test class in the new project.

  5. Add a test method to the test class.

  6. Use the Assert class to test the code to be tested.

  7. Run the tests using the Test Explorer in Visual Studio.

Here's an example of a simple unit test:

main.cs
using NUnit.Framework;

[TestFixture]
public class MyTests
{
  [Test]
  public void MyMethodTest()
  {
    // Arrange
    int x = 2;
    int y = 3;

    // Act
    int result = MyMathLibrary.MyMethod(x, y);

    // Assert
    Assert.AreEqual(result, 5);
  }
}
260 chars
20 lines

In the example above, we're using the NUnit framework to write a unit test for a method called MyMethod in a separate library called MyMathLibrary. The test checks whether the method returns the correct result when called with the arguments 2 and 3.

You can add more tests to the MyTests class using the same [Test] attribute. For more complex tests, you can also use setup and teardown methods using [SetUp] and [TearDown] attributes.

It's important to note that good unit tests should be fast, isolated, repeatable, and independent of external factors.

related categories

gistlibby LogSnag