当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Mocking Domain Model & Building Tests Without Repetition

问题描述:

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.

  1. The call to 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?
  2. I am testing that the method correctly responds if the repo does not find the DomainModel item. Then I test it correctly responds if the User cannot edit (well I will be when I solve point 1 above!). But after that, each test I write for the "Other stuff here" requires that I correctly set up the test to pass these first two checks. This seems cumbersome, and makes each test repeat the same code. Is there a better way?

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 DbSet<T> with 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: