Easy .NET Unit Test with Xunit + Moq + Autofac
Keep your code clean with Unit Test
After day by day, week by week, month to month headache to setup Unit Test, I decide to use some useful tools to give me more readable Unit Test. I decide to use XUnit, Moq, and Autofac. The XUnit as the main tools to run the unit test. I use Moq to help me test my code without real execution of my third parties dependencies. Why Autofac? Hemm… Not have specific reason of that, but I use great tools like Autofac.Extras.Moq, this library help me to have “Dependency Injection” to my unit test, it will bring my code more cleaner than I use manual instantiation my class. The setup also easy. “Give me the library references please!” Ok, calm, I will give you the references. Below the example when you use dotnet.
dotnet add package Autofac
dotnet add package Autofac.Extras.Moq
dotnet add package Moq
dotnet add package coverlet.collector
Great! Now, what should I do?
Ok, I will give you some example code
using Autofac.Extras.Moq;
using System;
using TweetyCore.Test.Data;
using TweetyCore.Utils.StringMatcher;
using Xunit;
namespace TweetyCore.Test
{
public class KMPTest
{
[Theory]
[ClassData(typeof(StringMatchingData))]
public void StringMatchingTest(string longString, string keyword, int expectedResult)
{
using (var mock = AutoMock.GetLoose())
{
var booyer = mock.Create<KMP>();
var result = booyer.Solve(longString, keyword);
Assert.Equal(expectedResult, result);
}
}
}
}
As you can see, I test the class that actually use interface to help me for Dependency Injection. It will different when you not use Autofac.Extras.Moq , you need to instantiate some dependencies. Since my code is simple so this have shorter code and more “readable” code. Xunit have great features that you can inject the data use DataClass. Why I use this? To help you test your code with some test cases! Sometimes you need more specific data to test your code. If I have many data, may I confirm that is my code more reliable? No! It’s not about the quantity, but more about quality. If you give data and test case that have extremely great quality, hopefully your code will “zero” bug. I use “zero” bug, since yeah, sometimes we missed something and boom , something happened quickly and you’re code shown a bug. Is it your fault? Not really. We already do our best, so don’t blame your self. :)
Okay, stop to story telling. I will continue this one. Okay, please now focus with the coverlet. I use this to bring me coverage report, what is this? It’s like how many percent that your test cover the flow, as example if you have branching like if, how many your code cover that branches, is it only cover the if condition, or else condition, or both? Yeah, the reporting will helping us to check which branches that not covered yet.
Explore more my example code here:
Have a nice day and happy coding!
Top comments (0)