Click here to Skip to main content
15,940,246 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a problem with unit tests in work(I'm new in unit test world). I have to test Provider who operates on ApplicationDbContext and DbSets but there aren't any interfaces of that and they are not virtual members.
I can't create them becouse application is to big to make changes.

So, I need to work on classes. Now i have problem.

I need to test somethink like that:
C#
public bool AddOrUpdateSomeDbSet(SomeClass doc)
       {
           this.db.SomeDbSet.AddOrUpdate(doc);

           try
           {
               this.db.SaveChanges();
               return true;
           }
           catch (Exception)
           {
               //TODO: logging
               return false;
           }
       }


So firsty I want to test a success try.
1. "db" is ApplicationDbContext.
2. I need to mock db.
3. db.SomeDbSet.AddOrUpdate(doc) must return some stuff to don't crash test.
4. db.SaveChanges() must return stuff too

And I have problem with point 3 and 4.

About point number 3:
I have somethink like that:
C#
// That doesn't work because there is no .Return after that code. I dont know why.
contextMock.Setup(x => x.SomeDbSet.AddOrUpdate(It.IsAny<SomeClass>())).Returns(SomeStuff)

About point number 4:
In context are two methods SaveChanges() and SaveChanges(string value)
C#
contextMock.Setup(x => x.SaveChanges("a")).Returns(1); // WORK
contextMock.Setup(x => x.SaveChanges()).Returns(1); // dont work
// An expression tree may not contain a call or invocation that uses optimal arguments - hmm? 


Can anyone help me with it?
Posted
Comments
virusstorm 9-Jul-15 13:18pm    
What version of EF are you using?
nerfsap 10-Jul-15 3:25am    
I do not know. Project is based on .net 4.5.
virusstorm 10-Jul-15 7:39am    
Find out what version of Entity Framework you are using. Easiest way is to right click on the reference in your project and select "Properties". The version number is critical as that will dictate the solution that you can use.
nerfsap 13-Jul-15 3:41am    
runtime verson : 4.0.3
version: 6.0.0.0

1 solution

You are running Entity Framework 6.0 which means you can take advantage of the this article:
Testing with a mocking framework (EF6 onwards)[^]

With EF 6, Microsoft changed the T4 file to generate everything using the keyword virtual. This allows the Moq framework to override the implementation of the methods and properties. You could do this with EF 5, but you would need to change the T4 file to allow for this.

I've implemented dozens of unit tests using this, so let me know if you run into a specific issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900