Cannot mock something like TableDomainService where the EntityContext is set in the class definition
I am trying to learn and implement TDD specifically using Moq and I have come up against a design that I can't figure out how to mock:
namespace RIACompletelyRelativeWebService.Web.Services
{
[EnableClientAccess]
public class AncestorDomainService : TableDomainService<AncestorEntityContext>
{
public AncestorDomainService()
{
//this.EntityContext = new AncestorEntityContext();
}
public IQueryable<AncestorEntity> GetAncestorEntities()
{
return this.EntityContext.AncestorEntities;
}
public void AddAncestorEntity(AncestorEntity entity)
{
this.EntityContext.AncestorEntities.Add(entity);
}
}
}
I think I need to mock the TableDomainService so that I can test my AncestorDomainService logic without firing up Azure. I tired something like this:
public class AncestorDomainService<TEntityConte开发者_运维知识库xt> : TableDomainService<TEntityContext> where TEntityContext is a TableEntityContext
But, the TableDomainService did not like having a generic being used. I also tried setting the EntityContext but it is read only. I have seen other people use the generic DomainService and the Repository design pattern, but since TableDomainService is what lets me use Azure tables behind the scenes, I think I have to stick with TableDomainService<>. Do I just have to fake the TableDomainService, the TableEntityContext and the TableEntitySet that is returned?
I don't know from the code above how the logic you want to test looks like, but you might try seperating your code (the code that you want to test) from the service itself.
You could try to abstract AncestorDomainService (introducing an IAncestorDomainService) and than use moq to mock IAncestorDomainService. Your logic would move to another class that has a dependency to IAncestorDomainService. I've done this with Linq2Sql (which seems to have a similar design and also returns IQueryable). I wouldn't try to mock the 'internals' of TableDomainService because this stuff is usually not designed for easy testing.
THe best solution, if you can afford the time, is to make your code fully testable. That means actually having the scripts necessary to setup an instance of Azure (real or local) with a known good state.
Since the whole point of your AncestorDomainService is to deal with Azure, mocking out its base class doesn't make much sense for a test effectiveness prespective. (Some people choose to optimize for test speed over effectiveness, but I think that's a waste of time.)
精彩评论