-3

I want to make a unit test for a game I have made, this code below is a simple move command for a grid-based game whereby when the user clicks a button the method is attached to, the player is moved up 1 row.

public String moveUp() {     //Allows player to move when corresponding command is entered
        int targetRow;
        int targetCol;

        targetRow = goldMiner.getRow() - 1;
        targetCol = goldMiner.getCol();

        String response = "";
        //If player does not have enough stamina they will not be allowed to move
        if (goldMiner.getStamina() <= 0) {
            response = "You are out of Stamina";
        //Stops player from moving outside of map
        } else if (targetRow < 0) {
            response = "You can't move that way";
        //If all parameters are met allows player to move in corresponding direction
        } else {
            PlayerMove(targetRow, targetCol);
            response = "You moved Up";
        }
        return response;
    }

Mirdon
  • 1
  • 1
  • 1
    Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then check the [help/on-topic] to see what questions you can ask. You might want to check other questions like https://stackoverflow.com/questions/8751553/how-to-write-a-unit-test – Progman May 31 '20 at 10:48

2 Answers2

2

For this method, you need three unit tests to cover all the code and you also need to mock goldMiner. The unit test would be like the below code:

public UnitTest {
  Mock GoldMiner goldMiner;
  @Autowired
  Service service; // assume moveUp method in this service 
  @BeforeEach
  void setUp() {
        goldMiner = mock(GoldMiner.class);
  }

  @Test
  public void shouldGetStamia_thenReturnOutof() {
   // You are out of Stamina
   when(goldMiner.getStamina()).thenReturn(-1);
   String response = service.moveUp();
   assertEquals(response, "You are out of Stamina");
  }

  //then another two cases are similar
  @Test
  public void shouldRowLessThanZero_thenCannotMove() {

  }

  @Test 
  public void shouldNormal_thenMoveUp() {

  }
}


PatrickChen
  • 1,350
  • 1
  • 11
  • 19
1

I suggest using JUnit5.

One simple example:

import org.junit.Test;
import org.junit.Assert;

public class Tests {

  @Test     //This is needed
  public void testOne() {
    String response = moveUp(); //Call method
    Assert.assertEquals("expectedValue", response); //Comparing expectedValue with response
  }
}

This method will test, whether response equals to the expected value (you will have to replace "expectedValue" with the real value).

I highly suggest to use an IDE like Eclipse to do Unit-tests. In Eclipse, you will have to import JUnit like explained here.

Please note: You can also have more than one test-method in Tests.java.