Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running JUnit test classes from another JUnit test class

I have two classes that I am testing (let's call them ClassA and ClassB). Each has its own JUnit test class (testClassA and testClassB respectively).

ClassA relies on ClassB for its normal functioning, so I want to make sure ClassB passes its tests before running testClassA (otherwise the results from testClassA would be meaningless).

What is the best way to do this? In this case it is for an assignment so I need to keep it to the two specified test classes if possible.

Can/should I throw an exception from testClassA if testClassB's tests aren't all passed? This would require testClassB to run invisibly and just report its success/failure to testClassA, rather than to the GUI (via JUnit).

I am using Eclipse and JUnit 4.8.1

Update: So far the best I've managed is a separate file with a test suite as shown below. This is still not quite what I'm after as it still allows ClassB tests to be run if ClassA fails some tests.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({testClassA.class, testClassBCode.class})
public class testClassB {
}
like image 616
David Mason Avatar asked Jan 23 '23 09:01

David Mason


1 Answers

Your unit tests should not depend on other tests.

One solution for your problem would be to mock ClassB in your ClassA's tests, in order to test its behaviour independently of the results of ClassB's tests.

I recommend you give mockito a try!

like image 173
mgv Avatar answered Feb 01 '23 00:02

mgv