Moq is very famous mocking framework in unit test
environment but AutoMoqer has certain advantages over Moq. In this article we
will try both Moq and AutoMoq and try to understand the difference.
Let’s implement one small scenario of Dependency injection where
we will implement concrete class from its abstraction (interface). Here is the
sample implementation.
namespace Code
{
public interface IMailService
{
void Send();
}
public interface ISMSService
{
void Send();
}
public class MessaginService
{
IMailService _mailService;
ISMSService _smsService;
public MessaginService(IMailService mailService)
{
this._mailService = mailService;
}
public MessaginService(IMailService mailService, ISMSService smsServices)
{
this._mailService = mailService;
this._smsService = smsServices;
}
public void Send()
{
_mailService.Send();
_smsService.Send();
}
}
}
The implementation is pretty simple, just we are injecting dependency
using constructor injection. Now, we want to unit test Send() function using
following code.
Implementation using
Moq framework
In case of Moq , we are mocking two interfaces to inject
both to second constructor. Then we are
calling Send() function to invoke this.
[TestClass]
public class UnitTestClass
{
[TestMethod]
public void Add_Test_Function()
{
var mockMail = new Mock<Code.IMailService>();
var mockSms = new Mock<Code.ISMSService>();
new Code.MessaginService(mockMail.Object , mockSms.Object).Send();
}
}
Now, here is small problem, If we like to inject one more
dependency to this Constructor we have to create another mock for same and have
to pass as parameter. In real time scenario developer might need to inject more
object based on requirement and for each addition we need to mock corresponding
abstraction.
AutoMoqer exactly solve this problem.
Implementation using
AutoMoqer.
Just we need to tell AutoMoqer what to create ! and
AutoMoqer will take care rest of the thing.
[TestClass]
public class UnitTestClass
{
[TestMethod]
public void Add_Test_Function()
{
//Implementation
using auto moqer
var autoMock = new AutoMoqer();
var fakeObject = autoMock.Create<Code.MessaginService>();
fakeObject.Send();
}
}
In code we are seeing that we are not creating mock for
abstraction (Interface) , so our unit test code need not to change even we add
another parameter to constructor/function.
No comments:
Post a Comment