2

I am new to JUnit. Currently have two separate JUnit test classes which both have 4 tests in, except one of the tests is identical for both test classes. Is there an easy way of somehow refactoring the code so that I can in a way 'import' the common test into both classes?

I have considered making a superclass to extract the common tests, however in this case it seems a bit overkill.

Any suggestions?

Many thanks.

Mahout
  • 414
  • 1
  • 3
  • 12

2 Answers2

1

It is context dependent but in general you should apply the same refactoring techniques as for your normal code:

  • it it makes sense for the two classes to inherit a parent class, extract the common code in a parent class
  • alternatively you can maybe extract the code in a Helper class that you call as necessary from your two test classes
  • or maybe you are testing the same thing with two different sets of data in which case using a parameterized test (data provider in TestNG) could be the solution
  • or maybe the fact that the code is the same is a coincidence because the tested classes don't have much in common in which case leaving the duplication may be better...
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Using a super class isn't completely unheard of. This could be a pain if however your hierarchy grows. I've seen webs of super classes be built only to find that the code is tough to follow when debugging (Especially when it isn't yours). It is still a viable solution though.

Extract the common method into a separate class and simply import it. If more code comes along that is common between the classes you can add more methods that might be common between the classes.

And if you aren't done with your unit testing you may find that these unit tests may change so keep in mind that you can also parameterize these methods later if you need to.

Hope this helps.

Dale
  • 1,613
  • 4
  • 22
  • 42
  • So in JUnit, does act of simply importing another test class mean that those tests are additionally run aswell as the ones in that class? – Mahout Oct 29 '15 at 10:39
  • You can simply make a test signature and make the method call within the test. The common code would simply be most of the common test code. – Dale Oct 29 '15 at 10:54