I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?
views:
81answers:
5Inject your database dependency into your class using IoC. This should be done by handing it a repository object in the constructor of your class. Note that you don't necessarily need an IoC container to do this. You just need a repository interface and two implementations of your repository.
Note: In Python IoC works a little differently. See http://code.activestate.com/recipes/413268/ for more information.
This is kind of brute force but it works. Have an environmental variable UNIT_TEST that your code checks, and set it inside your unit test driver.
Use some sort of database configuration and configure which database to use, and configure the in-memory database during unit tests.
As Robert Harvey points out, it would be better if you could hand the settings to the component instead of having the component looking it up itself. This allows you to swap the settings simply by providing another object, i.e
TestComponent(TestSettings())
instead of
TestComponent(LiveSettings())
or, if you want to use config files,
TestComponent(Settings("test.conf"))
instead of
TestComponent(Settings("live.conf"))
I recommend using a mocking library such as mocker. And FYI, writing your code to check and see if you're in a unit test is a bad code smell. Your unit tests should be executing the code that's being tested as you wrote it.