开发者

Is there a way to tell whether a function is getting executed in a unittest?

开发者 https://www.devze.com 2022-12-09 15:44 出处:网络
I\'m using a config f开发者_运维百科ile 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 using a config f开发者_运维百科ile 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?


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.


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


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.


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.


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"))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号