views:

40

answers:

3

Is it ok to use a container to create the objects that are going to be tested? Or should I build them manually?

+2  A: 

Yes, it's okay and good and will keep kittens from being killed. Keep in mind that IoC containers are useful for three things:

  1. object composition.
  2. lifecycle management.
  3. interception.

If you are in need of any of these three items, why not let a tool built for the job do it for you?

Jason
Great thanks =)
HappyDeveloper
+1  A: 

Yes and no.

You certainly can use one, but you shouldn't have to (Containers are great for composing complex systems, but in a unit test those complexities shouldn't be present).

Why are you considering it? Would hand-rolling the equivalent just be tedious (it always is), or would it be hair-pullingly difficult? If it's the latter then you're putting duct-tape on a problem.

STW
Nah it's not that difficult, but the question arised and I wanted to know if there was a rule like 'NEVER use a container when testing', or 'if the objects will be created with a container in the real app, they should be created with a container in the tests'Thanks for the answer, though I still don't know if it is bad practice. I know I shouldn't HAVE to, but anyway..
HappyDeveloper
Sounds like you should be fine; it's always about keeping things in check. For a decent rant about IoC/DI going to far, check out http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion
STW
@STW: See this reply: http://ayende.com/blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx as well as http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx
Jason
A: 

Whichever way will give you the most accurate (closest to real use case) and yet lightest (free of all dependencies) instance of the unit to be tested. If you build your classes smartly - mostly not doing - you should be able to instantiate them without dependencies and therefore testing should be a snap. If you want to run tests against a group of classes at one time (to see how they work together...i dunno if many do this, though), then perhaps a factory (a design pattern which encapsulates instantiation) with a some stubs or drivers would do the trick.

http://wiki.answers.com/Q/What_is_stubs_and_drivers_in_software_testing

So yea, not a "container" per se, but potentially some other pattern or class you are assigning the sole responsibility of recreating the ideal testing situations.

Montagist