0

So I have to create one Integration testing and I require to setup a code only once and not before each tests. I checked many articles and it seems JUnit don't provide anything which will help us to code like that. I came across one efficient way to solve this by using below structure but it didn't worked for me.

private static boolean setUpIsDone = false;

@BeforeEach
public void createGame() {
    if (setUpIsDone) {
        return;
    }
//setupcode
setUpIsDone = true;
}

While this should work, it didn't worked for me.

My Integration test code -

public class GameServiceIntegrationTest {

@Autowired
private GameService gameService;
@Autowired
UserService userService;

private Game testGame;
private long gameId=-1;
private static boolean setUpIsDone = false;

@BeforeEach
public void createGame() {
/*
        if (setUpIsDone) {
            return;
        }*/

    User testUser = new User();
    testUser.setUsername("gamer");
    testUser.setPassword("123");
    testUser = userService.createUser(testUser);

    List<Long> playerIdList = new ArrayList<>();
    playerIdList.add(testUser.getId());


    gameId = gameService.createGame(playerIdList);
    testGame = gameService.getExistingGame(gameId);
//        setUpIsDone = true;
}

    @Test
public void chooseWord(){

    System.out.println("game id here1 ->"+gameId);
    int chooseIndex = 1;
    gameService.chooseWord(gameId,chooseIndex);
    testGame = gameService.getExistingGame(gameId);
    assertEquals(testGame.getWordIndex(),0);

}

I want to use gameId variable in every other test that I continue further. If I am using the current version of code, I am getting the exception that object is already created and is failing. So it seems that setup is being executed before every test and the last test value persists.

And if I uncomment the code for setupIsDone process, I am getting gameId as -1 in other test classes. So it seems that the value is not persisting after the first test.

If there is any way to save the data in setup phase for testing overcoming above problem?

Prasun Saurabh
  • 47
  • 1
  • 10
  • You can use `BeforeAll` – 0xh3xa May 02 '20 at 22:04
  • Plz check this: https://stackoverflow.com/questions/20295578/difference-between-before-beforeclass-beforeeach-and-beforeall – 0xh3xa May 02 '20 at 22:04
  • @BeforeAll requires me to turn the setup into static code which i can't because of my requirement and that is why I was trying to implement the static boolean flag – Prasun Saurabh May 03 '20 at 06:12

1 Answers1

0

How about declaring testGame as static and then checking to see if testGame == null at the top of createGame()?

fram
  • 1,551
  • 1
  • 7
  • 7