Looking for some clarification regarding testing. I have the following method in my Service layer:
readonly IDomainModelRepository domainModelRepository;
public DomainModelDetailsDto Edit(int DomainModelID, IPrincipal User)
DomainModel myDomainModel = domainModelRepository.Find(DomainModelID);
if ((myDomainModel == null) || (!myDomainModel.UserCanEdit(User)))
throw new UnauthorisedException();
// Other stuff here...
Now I am building a suite of tests but have hit a couple of snags.
myDomainModel.UserCanEdit(User)cannot be mocked as DomainModel is not implementing any interface. It becomes even more complicated because the logic contained within UserCanEdit actually checks fields on other domain models within its graph. So how can I easily set this up to return a set value to allow me to test the Service?
Perhaps the problem is that my code itself needs to be refactored in order to facilitate easier testing. If so, all advice appreciated!
If you want to test I think you need to use an interface on the
myDomainModel otherwise you cant mock it.
I know this is a very controversial opinion but more and more people think Repository patter is an anti patter because it creates more problems than it resolves.
I personally use Entity Framework and change the TT files to generate the Context and the interface than in all my application I only use the interface.
To test I just mock the interface and I'm able to test everything. One of the changes I do is to change all the
IDbSet<T>. Finally I created a Test Helper with a function that receives an
ObservableCollection and returns an
IDbSet and I'm able to validate everything.
You can stub
UserCanEdit by making that method
virtual and having a derived test class which overrides it. Your mocked repository can then return an instance of this test class set to return true or false depending on what you want to test.