I’m using the Unit Of Work Pattern with my data layer.
public interface IUnitOfWork{
IRepository<Class1> Class1s {get;}
IRepository<Class2> Class2s {get;}
...
}
public interface IRepository<T> where T:class{
IQueryable<T> GetAll();
}
This is working as expected with my codebase; however, I’m having issues testing this
in my service layer.
public class SomeService{
private readonly IUnitOfWork uow;
public SomeService(IUnitOfWork u){
uow = u;
}
public IEnumerable<ViewModel1> GetViewModel(){
var result1 = uow.Class1s.GetAll();
var result2 = uow.Class2s.GetAll();
var query = from r1 in result1
from r2 in result2
where r1.key == r2.key
select new ViewModel1{...};
return result;
}
}
(The test) using Moq
[Test]
public void TestMethod(){
var uow = new Mock<IUnitOfWork>();
uow.Setup(u => u.Class1s.GetAll()).Returns(new []{ new Class1{...}}.AsQueryable());
uow.Setup(u => u.Class2s.GetAll()).Returns(new []{ new Class2{...}}.AsQueryable());
var service = new SomeService(uow.Object);
var result = service.GetViewModel();
Assert.AreEqual(1,result.Count());
}
The test is throwing an exception saying that result1 (and result2) are null. I realized this was because I’m not directly instantiating the properties. But I was wondering if there was a way to not have to also mock the properties inside of the mock. If not with Moq then maybe some other mocking framework?
No, Moq won’t help you here. You’ll have to set them manually (although you can mock them aswell):
Note that you’ll now have to do
.SetupforGetAllonclass1Mockandclass2Mock:If you want to have this kind of control over your mocks, there’s no shortcuts I’m afraid.
Note: even though it wont help in your case (since you want direct control over mocks), AutoFixture with Moq is definitely worth checking out in similar scenarios.