C# – Can’t pass decimal parameter in DataTestMethod

I have a parameterized unit test with decimal parameters. When I run the test, I get the following exception: System.ArgumentException: Object of type ‘System.Double’ cannot be converted to type ‘System.Decimal’. Solution Change the parameters to doubles and convert them to decimals inside the test method. Why is it throwing an exception? You have to pass … Read more

C# – Parameterized tests with MSTest v2

There are two steps for parameterizing a unit test when using the MSTest v2 framework (built-in default): Here’s an example: Parameterized unit tests are useful because you only need one test method for multiple test cases instead of one test method per test case. It’s a simple way to declutter your unit tests and make … Read more

C# – How to test that your code can handle another culture’s date format

Let’s say you have code that converts a string to a DateTime with DateTime.Parse(): By default, DateTime.Parse() uses CultureInfo.CurrentCulture to figure out the date format. The current culture ultimately comes from your OS settings. So when you run this code on a computer that is using the en-US locale, the current culture will automatically default … Read more

Moq – Return different values with SetupSequence

When you’re mocking a method that’s called multiple times, you may want to change the behavior of the method each time it’s called. The way you do this with Moq is by using SetupSequence(), like this: Note: You can also make it throw an exception in the sequence. Example of code I want to test … Read more

C# – How to unit test async methods

Let’s say you have the following async method you want to test: Here’s how to unit test this: This is awaiting the method you’re testing. To await it, you must make the unit test method return async Task. This example is a bit simplistic. In the real world when you are working with async methods, … Read more

How to mock static methods

The need to mock static methods in order to add a unit test is a very common problem. It’s often the case that these static methods are in third-party libraries. There are many utility libraries that are completely made up of static methods. While this makes them very easy to use, it makes them really … Read more