2

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?

duffymo
  • 305,152
  • 44
  • 369
  • 561
BlueLettuce16
  • 2,013
  • 4
  • 20
  • 31
  • What is the exact result of running the line of code above? Do you get a NoClassDefFoundError or ClassNotFoundException or something else? – Hakan Serce May 17 '12 at 13:20
  • The tests class is running, however I get null pointer exception - it's impossible to instantinate SomeOtherClass as a member of MyClasNameTest. However I have found one solution and I think that's ok, however I haven't tested it yet - I'll do it tomorrow and then post my reply. – BlueLettuce16 May 17 '12 at 17:38

3 Answers3

1

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");
}
Community
  • 1
  • 1
jmruc
  • 5,714
  • 3
  • 22
  • 41
  • Thank you for your solution, however in my project I have much more than 200 classes to mock and most of them are quite large, so mocking them won't be easy :( – BlueLettuce16 May 17 '12 at 17:44
1

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/

Cedric Beust
  • 15,480
  • 2
  • 55
  • 55
0

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561