How do I perform unit testing using NUnit or MSTest

Unit testing is a crucial part of software development that helps ensure your code behaves as expected. Using frameworks like NUnit or MSTest in C#, you can create and run tests to verify the functionality of your code. Below is an example demonstrating how to perform unit testing using these frameworks.

Unit Testing with NUnit

NUnit is a popular unit-testing framework for C#. Here's a simple example:

using NUnit.Framework; [TestFixture] public class CalculatorTests { private Calculator _calculator; [SetUp] public void Setup() { _calculator = new Calculator(); } [Test] public void Add_WhenCalled_ReturnsSumOfArguments() { var result = _calculator.Add(2, 3); Assert.AreEqual(5, result); } } public class Calculator { public int Add(int a, int b) { return a + b; } }

Unit Testing with MSTest

MSTest is another testing framework provided by Microsoft. Here's how you would write a similar test using MSTest:

using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class CalculatorTests { private Calculator _calculator; [TestInitialize] public void Setup() { _calculator = new Calculator(); } [TestMethod] public void Add_WhenCalled_ReturnsSumOfArguments() { var result = _calculator.Add(2, 3); Assert.AreEqual(5, result); } } public class Calculator { public int Add(int a, int b) { return a + b; } }

Unit Testing NUnit MSTest C# Testing