Instanciation of class to be tested in test class in Java

Viewed 54

What is the best practice in order to get an instance of the class to be tested in the test class?
Is it better to instantiate it manually with a

ClassToBeTested classToBeTested = new ClassToBeTested();

inside the test-class

OR

get it from the Spring context, like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {

  @Autowired
  MyService service;
...

}
2 Answers

There is a simple rule in programming, that can guide such questions:

you don't do something because you can, but because it makes sense to do it.

Meaning: you always strive to write the most minimalistic, simplistic code that solves your problem.

So when

ClassToBeTested classToBeTested = new ClassToBeTested();

is sufficient for your testcase, and gives you all you need to write a nice test, then you use that.

If you need something that you get "easier" from that annotation-based DI approach, then you use that approach.

Having said that, there are also conventions. When the "typical" thing that most programmers would do ... is to use the annotation-approach, then that is what you should use.

Better try to use auto wiring to be aligned with more clean and test friendly code and future change.

using "new" can be problematice in future but auto-wiring may save you

Related