I’m facing an issue I don’t quite understand.
I’m developing an application in C#/ASP.net using the Entity Framework.
I’m trying to do some unit testing on it, and therefore I need to mock one of the object, and I can’t seem to work it out.
Here is the class I want to mock:
http://pastebin.com/pMypAM7G
This class returns a new DataSourceContainer if no one currently exists, and returns the existing one otherwise (needed it to avoid having multiple contexts)
Here is the interface (which only purpose is to allow mocking) : http://pastebin.com/LRYVdA9j
Here is the fonction I am trying to test : http://pastebin.com/naVsV3FX
And here is the test fonction : http://pastebin.com/dY4ERzSJ
When I try to do the test, I get an error on the Database class, within the getter, because there is no HttpContext (which is logical).
What I don’t get is that the getter is supposed to be mocked.
I’ve tried to look it up on the internet but I can’t figure out what I’m doing wrong, so if someone could help me out on this one, I’d be really grateful. Thanks !
You have not imeplemented your code properly to support unit testing – you are creating external object (
Database) in your method. Also, you are not usingIDatabaseinterface, but concrete implementation ofDatabaseYou should read at least about Dependency Injection.
This short example may help you understand problems in your code
This time, Connexion is loosely bound to IDatabase interface, not to its implementation. At runtime, you would supply
new Database()as its value, but at test-time, mocked implementation.