BlueLettuce16
BlueLettuce16

Reputation: 2103

How to inject custom class object into Junit environment?

I am running JUnit from my code:

    Result result = JUnitCore.runClasses(MyClassNameTest.class);

The problem that I'm dealing with is taht MyClassName is dependent on some other class - let's say it's name is SomeOtherClass and I need that class to inject its instace somehow into "JUnit runtime" to be visible for MyClassName. Is it possible?

Upvotes: 2

Views: 2119

Answers (3)

Cedric Beust
Cedric Beust

Reputation: 15608

Consider using dependency injection with a framework such as Guice. Here is an introduction that should give you a good idea of what it is and how to use it:

http://beust.com/weblog/2012/03/25/dependency-injection/

Upvotes: 1

jmruc
jmruc

Reputation: 5836

You should not need the other classes to do your test - I suggest that you mock them. Mockito is what I would choose, and this question has a nice discussion about various options. If you cannot do your testing by mocking other dependencies, I seriously suggest that you refactor your code, so that it can be done.

If you really do not want to go that (right) path, you could try some dependency injection framework like Spring, and have a separate context for each of your test classes. At junit4 you can use @BeforeClass

@BeforeClass
public void initSpring()
{
    Application context = getTestAppContext();//should be unique config for this class
    requiredProperty  = contex.getBean("someProperty");
}

Upvotes: 1

duffymo
duffymo

Reputation: 308988

Sure it's possible.

One way would be to have a Map, where the key is the Class or name of the parent class and the value is the Class or name of the child. Do the lookup and pass it to a factory for instantiation.

Upvotes: 0

Related Questions