views:

81

answers:

5

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?

+3  A: 

Inject 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.

Robert Harvey
I'll go with this. As Jason Baker pointed out below, checking to see if I'm in a unit test is poor practice.
Robbie
I gave you +1 for this answer, but I would really like to see a real example. That recipe is kind of hard for me to follow.
steveha
A: 

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.

DVK
This answers his question. But the entire idea of checking to see if you're in a unit test or not is *bad*.
Jason Baker
Good point. But not everyone has access to decent mocking frameworks and test harnesses.
DVK
+1  A: 

Use some sort of database configuration and configure which database to use, and configure the in-memory database during unit tests.

Lennart Regebro
A: 

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"))
disown
FYI, I've updated your code so that it's Python code rather than (I'm assuming) C# or Java.
Jason Baker
A: 

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.

Jason Baker