1

We are looking at how to use dependency injection into unit tests (using JSR-330 syntax but without explicitly specifying the engine in the basic tests if that matters), and we have used junit 4 so far and been very pleased with it, but it appears that it is not designed for dependency injection in the tests.

Question is, whether junit is well suited for tests to be run in a dependency injection context, or if I should just switch to TestNG?

Just to clarify: We are trying to be DI-engine agnostic, and currently looking at dagger.

I would appreciate if opinions were backed up with fact, thanks.

Thorbjørn Ravn Andersen
  • 68,906
  • 28
  • 171
  • 323
  • http://stackoverflow.com/questions/2425015/how-to-access-spring-context-in-junit-tests-annotated-with-runwith-and-context maybe this will help – dantuch Aug 13 '13 at 11:34
  • @ThorbjørnRavnAnderser this statement : "but it appears that it is not designed for dependency injection in the tests" makes very little sense. What does junit has to do with DI? Can u explain a bit may be> – Eugene Aug 13 '13 at 11:44
  • @Eugene I would like to put something like "@Inject Foo foo" in my junit test and have something put in there as part of the test run. – Thorbjørn Ravn Andersen Aug 13 '13 at 11:51
  • @ThorbjørnRavnAndersen of course the obvious answer is, if you have spring... :) but I assume u know that already. You either way need a "context" of where this injected property will come from. – Eugene Aug 13 '13 at 11:54
  • If this is a unit test, then don't use a DI framework. That would make it not a unit test, but an integration test. If this is actually an integration test, then use whatever framework you are going to use in the real application. That's what integration tests are for. – Tom Anderson Aug 13 '13 at 14:08
  • On which subject: http://picocontainer.codehaus.org/tests-use-container-antipattern.html – Tom Anderson Aug 14 '13 at 10:41

3 Answers3

1

Assuming you are using Spring framework

You can annotate your Junit test classes like this:

@RunWith( SpringJUnit4ClassRunner.class )  
@ContextConfiguration( "classpath:appTest-context.xml" )
public class AppServiceTest{
   ...
   ...
}

And inside appTest-context.xml have your regular Spring config stuff for injecting all the dependencies.

anubhava
  • 664,788
  • 59
  • 469
  • 547
0

Junit have @RunWith annotation, check org.springframework.test.context.junit4.SpringJUnit4ClassRunner

as example of implementation DI in Junit tests

0

I am not sure about the JUnit (but by seeing other answers seems like it is also possible with JUnit) but in our application we used TestNG for running the test cases and we were successfully able to inject the dependencies.

saurav
  • 3,173
  • 1
  • 20
  • 32