Reputation: 327
I am trying to make some Junit tests for a tic tac toe board. I know how to test one function at a time, but my problem is that in order to check some function, previous functions must be called.
For example, in order to check a winner, you have to call the function "PlaceMarker" function multiple times. The specific one I'm on is checking to make sure the bool function "CheckSpace" returns false when there is already a marker in the spot its checking. I currently have
public class TestGame {
private GameBoard board;
@Before
public void setUp() {board = new GameBoard();}
@After
public void tearDown() {board = null;}
@Test
public void testRewritingOverSpace() {
assertEquals("Placing (1, 1), then checking space (1, 1)", false,
board.placeMarker(new BoardPosition(1, 1, 'X')),
board.checkSpace(new BoardPosition(1, 1, 'O'));
This is giving me a error. So in short, how do you make a JUnit test case in which you have to call multiple functions.
Upvotes: 0
Views: 1502
Reputation: 140457
To answer the question: you go step by step. Especially when you consider TDD, you work like this:
And yes, that could mean that your code looks like:
@Test
public void testFirstFeature() {
... one line of setup
... invoke method on object under test
... assert something
} ...
@Test
public void testMoreAdvancedFeature() {
... multiple
... lines
... of setup
... invoke method on object under test
... assert something
}
And you will probably find that your later test cases do actually test/verify behaviour that is already covered by tests you wrote earlier on. Then you can step back and ask yourself: "is there some merit in keeping this earlier tests - or can I safely throw them away?"
You are correct, balancing is required here: having multiple tests that do the same/similar things leads to "duplication". On the other hand - the more tests you have, the easier it will be for you to change small things here and there - and then receive immediate feedback.
Thus: there is no single answer to this. It is all about context and engineering judgement.
Upvotes: 2