I'm building a card game which is only relevant because of the examples given below.
I consider myself a fairly experienced C++ programmer, with considerable TDD experience in that language; most recently using UnitTest++. I am new to Java, and intend to target Android once I get my Java legs.
What I want to do is something akin to this UnitTest++ setup:
class DeckTest
{
public:
Deck deck;
};
class EmptyDeck : public DeckTest
{
// doesn't need to do anything for this simplified example
};
TEST_FIXTURE(EmptyDeck, HasNoCards)
{
CHECK_EQUAL(0, deck.GetNumCards());
}
TEST_FIXTURE(EmptyDeck, ThrowsOnCardAccess)
{
CHECK_THROWS(InvalidCardIndexException, deck.GetCard(0));
}
class DeckWithCards : public DeckTest
{
void setUp()
{
// load deck with a bunch of cards
}
};
TEST_FIXTURE(DeckWithCards, FirstCardIsAccessible)
{
// ...etc.
Now, in C++ I'd just throw this all into a DeckTest.cpp file and be done; multiple fixtures all testing one client class. Makes sense to me.
However, in Java, I feel like I want to do something similar:
class DeckTester {
Deck deck = new Deck();
}
class EmptyDeck extends DeckTester {
@Test
public void EmptyDeckHasNoCards() {
assertThat(deck.GetNumCards(), equalTo(0));
}
@Test(expected=Deck.EmptyDeckException.class)
public void EmptyDeckThrowsWhenGettingCard() throws Deck.EmptyDeckException {
Card card = deck.GetCard(0);
}
}
class DeckWithCards extends DeckTester {
@Before
public void AddCards() {
Card card = new Card(Card.Type.k_missed);
deck.AddCard(card);
// ...or similar...
}
}
public class DeckTests {
// What goes here?
}
...since I can only have one public class per module I figured I'd try to build a suite or something, but I can't figure out the way to do it. I'm using the various AllTests.java in the junit-4.8.2 distro to guide me, but the one that looked most promising (org.junit.tests.AllTests
) gives me compile errors when I try to mimic it.
I figured the preferred way would be to have internal classes, but junit doesn't pick those up either. It feels yucky to me to have to split these out into different files, but maybe that's just the Java way?
Tips most appreciated, thanks!
Edit: Largely I'm curious about file structure. Given the lack of response, I'm starting to think that it's not particularly feasible to have all of these things in one file. So, when developing tests like this, how do people structure them in Java? Would I create a test.deck package, with a number of test classes containing only a small number of tests, or do folks just go ahead and embrace the duplication and jam them all into one test class? (Am I giving up too easily by feeling spoiled by the ease of use of UnitTest++, where I include one file to get all of its features and where I can have a bunch of classes that test a feature in one file?)