Everyone wants to write bug free code which is good but the problem is there
are few bugs which are revealed at the time of integration or in future after updating
code that has dependencies.
Unit Tests help us prevent such situation right after you are done with
your changes. UTCs cannot catch all the errors but they minimize the bugs from production
You can test your code with some sample data right after you write it. I
have worked on software which has more than 10000 UTCs and most part of the
application can be tested using those UTCs only. These UTCs catch integration
level error or check some corner scenarios.
UTCs are as good as their writer. It all depend on how many scenarios
you can cover and quality of Test Data.
It’s time for example-
First add a xUnit Test project in your solution
This will create a UnitTest1.cs file in your project with Test1() method. In xUnit project Fact and Theory are used in place of TestMethod attribute
Now it’s time to include moq nugget
After importing it in your class you are all set for your first test
method
using Xunit;
using CrossProjectDemo;
using Moq;
namespace Struts.Tests
{
public class UnitTest1
{
[Fact]
public void Test1()
{
var moc = new Mock<CustomLoops>();
var car = new
Car(moc.Object);
car.Caller(null, 9);
}
}
}
Here you can see I am
using Mock class to create a dummy object or class CustomLoops which is called
mocking a class
Let’s see what this moc
variable has
Now It’s time to run the Mock method as well
[Fact]
public void Test1()
{
var moc = new
Mock<CustomLoops>();
moc.Setup(mc =>
mc.mockingMethod()).Returns(200);
var car = new
Car(moc.Object);
car.Caller(null, 9);
Assert.Equal(200,
car.mockingMethod());
}
As you can see UTC ran
successfully and Assert passed, Now see one thing
public virtual int mockingMethod()
{
return 110;
}
The mocking method is
returning only 110. So how can the Assert pass.
In this example I have
mocked the method mockingMethod of CustomLoops class and return 200 from it. To
mock a method it must be virtual.
Now coming back to
attributes. xUnit uses Fact and Theory as attribute to mark a method test
- Fact is used when you want to run
a method only once
- Theory is used when you want to run a method multiple times
- You can use InlineData() attribute to pass various data to the test method
Now you know you can mock
classes and methods in .net using moq and xUnit. These are very powerful library
for TDD. With use of dependency injection testing can be done more effectively
and it also reduces dependency among projects.
That’s it from this post
Thanks