To write a unit test in C#, follow the steps below:
Create a new class library project in Visual Studio.
Add a reference to the project that contains the code to test.
Add a reference to the NUnit or MSTest framework.
Create a test class in the new project.
Add a test method to the test class.
Use the Assert class to test the code to be tested.
Run the tests using the Test Explorer in Visual Studio.
Here's an example of a simple unit test:
main.cs260 chars20 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.
gistlibby LogSnag