Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with ServiceLocator

I am doing a unit test on a class that uses the unity dependency injection framework.

This returns null: ServiceLocator.Current.GetInstance();

How can I get it to return a mock object or just the object itself?

like image 520
zachary Avatar asked Oct 15 '09 15:10

zachary


People also ask

Which testing is used for unit testing?

Unit tests can be performed manually or automated. Those employing a manual method may have an instinctual document made detailing each step in the process; however, automated testing is the more common method to unit tests. Automated approaches commonly use a testing framework to develop test cases.

What is unit testing with real time example?

An example of a real-world scenario that could be covered by a unit test is a checking that your car door can be unlocked, where you test that the door is unlocked using your car key, but it is not unlocked using your house key, garage door remote, or your neighbour's (who happen to have the same car as you) key.

Can unit tests use databases?

Unit tests shouldn't depend on infrastructure 🔗There's no way to test this function without a database connection available at the time of testing. If a new developer clones the project they will need to set up a database before they can successfully run the unit tests.


1 Answers

You could make use of Poor Man's injection. Create a default constructor which retrieves the dependencies from the service locator, and forward those dependencies to a "real" constructor which takes them as parameters. That takes care of production situations.

Then when testing the class in question, pass in a fake/mock version of the dependencies to the "real" constructor, bypassing the default one altogether.

like image 121
Grant Palin Avatar answered Nov 10 '22 16:11

Grant Palin