views:

220

answers:

2

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 {
}
+3  A: 

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!

mgv
In this case, as it's an assignment, I can't rely on my lecturers having mockito - essentially they're just going to copy my Java package into their project, run their tests on my classes, and run my tests on their classes. (for future reference obviously I'd like to know the best way to approach such things).Although it may not be ideal, at the moment I'm just looking for a way (if one exists) to say`//don't run this test unless ClassB has passed its tests`without having to rely on the tester seeing my comment.
Dr. Monkey
I don't think you can do it in JUnit. You can specify test order by using OrderedSuite add-on for JUnit, TestNG or other testing frameworks.
mgv
A: 

You should try testng framework which allow this kind of dependency testing.

fastcodejava
As in earlier comment: this is for an assignment and JUnit tests are a requirement.
Dr. Monkey