Question

How can I make a test case with Junit? import java.util.ArrayList; import board.Board; public class Pawn...

How can I make a test case with Junit?

import java.util.ArrayList;

import board.Board;

public class Pawn extends Piece{

   public Pawn(int positionX, int positionY, boolean isWhite) {
       super("P", positionX, positionY, isWhite);
   }

   @Override
   public String getPossibleMoves() {
       ArrayList<String> possibleMoves = new ArrayList<>();
      
       //check side, different color pawns go on different ways
       if(isWhite) {
           if(positionX != 7 && positionY != 0) {
               if(Board.board[positionX + 1][positionY - 1] != null && !Board.board[positionX + 1][positionY - 1].isWhite()) {
                   possibleMoves.add(Board.positionToChessPosition(positionX + 1, positionY - 1));
               }
           }

           if(positionX != 7 && positionY != 7) {
               if(Board.board[positionX + 1][positionY + 1] != null && !Board.board[positionX + 1][positionY + 1].isWhite()) {
                   possibleMoves.add(Board.positionToChessPosition(positionX + 1, positionY + 1));
               }
           }
           if(positionX != 7) {
               if(Board.board[positionX + 1][positionY] == null) {
                   possibleMoves.add(Board.positionToChessPosition(positionX + 1, positionY));
               }
           }
          
           if(positionX == 1 && Board.board[3][positionY] == null) {
               possibleMoves.add(Board.positionToChessPosition(3, positionY));
           }
       }else {
           if(positionX != 0 && positionY != 0) {
               if(Board.board[positionX - 1][positionY - 1] != null && Board.board[positionX - 1][positionY - 1].isWhite()) {
                   possibleMoves.add(Board.positionToChessPosition(positionX - 1, positionY - 1));
               }
           }
           if(positionX != 0 && positionY != 7) {
               if(Board.board[positionX - 1][positionY + 1] != null && Board.board[positionX - 1][positionY + 1].isWhite()) {
                   possibleMoves.add(Board.positionToChessPosition(positionX - 1, positionY + 1));
               }
           }
           if(positionX != 0) {
               if(Board.board[positionX - 1][positionY] == null) {
                   possibleMoves.add(Board.positionToChessPosition(positionX - 1, positionY));
               }
           }
          
           if(positionX == 6 && Board.board[4][positionY] == null) {
               possibleMoves.add(Board.positionToChessPosition(4, positionY));
           }
       }
      
       String result = "";
      
       if(!possibleMoves.isEmpty()) {
           result += possibleMoves.get(0);
          
           for(int i = 1; i < possibleMoves.size(); i++) {
               result += ", " + possibleMoves.get(i);
           }
       }
      
       return result;
   }

   @Override
   public String toString() {
       return "P" + Board.positionToChessPosition(positionX, positionY);
   }
}

public abstract class Piece {
   protected String name;
   protected int positionX, positionY;
   public boolean isWhite;
  
  
   public Piece(String name, int positionX, int positionY, boolean isWhite) {
       this.name = name;
       this.positionX = positionX;
       this.positionY = positionY;
       this.isWhite = isWhite;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public int getPositionX() {
       return positionX;
   }

   public void setPositionX(int positionX) {
       this.positionX = positionX;
   }

   public int getPositionY() {
       return positionY;
   }

   public void setPositionY(int positionY) {
       this.positionY = positionY;
   }

   public boolean isWhite() {
       return isWhite;
   }

   public void setWhite(boolean isWhite) {
       this.isWhite = isWhite;
   }
  
   public abstract String getPossibleMoves();
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,

Please find the answer below:

-------------------------------------------------

There are main 3 versions in Junit that are widely used.

  • JUnit 3
  • JUnit 4 -> Vintage
  • Junit 5 -> Jupiter

Junit3 doesn't have any annotations and is old now.
JUnit 4 introduced annotations i.e @Test, @Before, @After etc.
JUnit 5 the current version introduced more annotations and basically divided the monolithic junit jar into three APIs.

We need to annotate a method as @Test to mark it as a test method.

Things we do in JUnit testing ina high-level

Perform Setup.-> instantiate a class like chessboard, pawn etc.
Perform Action. In a test method you basically perform some action and validate using assertions.( Assert class)
Perform CleanUp.-> nullify objects to make tests independent to each other.

Create JUnit Test case:

Right click the class >> New >> JUnit Test Case.

Choose all method stubs.

Class Under Test choose Pawn class.

In the next screen choose which methods to test.

Hit Finish.

---------------------------------

Implement the test methods , setup and tear down stubs.

Run and check the junit test results.

--------------------------------

Sample Junit test case :

Note that: You need to perform test actions and assertions as per the board class.

Positive testcase:

Basically create a Pawn at some point x,y and color balck and white and test the legal moves.

Negative testcase:

Basically create a Pawn at some INVALID point x,y say 10 , 10 and color brown and test how the method reponds.

---------------------------------------------

package test;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import chess.Pawn;

/**
*
*/

/**
* @author
*
*/
class PawnTest {
   Pawn _pawn;
   Board _board;

   /**
   * @throws java.lang.Exception
   */
   @BeforeAll
   static void setUpBeforeClass() throws Exception {
       //Setup a chess board here.
   }

   /**
   * @throws java.lang.Exception
   */
   @AfterAll
   static void tearDownAfterClass() throws Exception {
   }

   /**
   * @throws java.lang.Exception
   */
   @BeforeEach
   void setUp() throws Exception {
       //Creating a white Pawn @ 2,2
       // This runs before the test method
       _pawn = new Pawn(2, 2,true);
   }

   /**
   * @throws java.lang.Exception
   */
   @AfterEach
   void tearDown() throws Exception {
       // making the pawn null
       // This runs after the test method
       _pawn = null;
   }

   /**
   * Test method for {@link chess.Pawn#getPossibleMoves()}.
   */
   @Test
   void testGetPossibleMoves() {
       System.out.println(_pawn.getPossibleMoves());
       // Check the valid moves here using asertions.
       // look at the org.junit.Assert.
       // Junit 5 : org.junit.jupiter.api.Assertions
   }

   /**
   * Test method for {@link chess.Pawn#Pawn(int, int, boolean)}.
   */
   @Test
   void testPawn() {
       fail("Not yet implemented");
   }

}

----------------------------------------------------


Hope this helps.

Add a comment
Know the answer?
Add Answer to:
How can I make a test case with Junit? import java.util.ArrayList; import board.Board; public class Pawn...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write Junit test for the following class below: public class Player {       public int...

    Write Junit test for the following class below: public class Player {       public int turnScore;    public int roundScore;    public int lastTurnScore;    public String name;    public int chipPile;       public Player (String name) {        this.name = name;        this.turnScore = 0;        this.chipPile = 50;    }          public int getChip() {        return chipPile;    }       public void addChip(int chips) {        chipPile...

  • Write Junit test for the following class below: public class Player {       public int turnScore;    public int roundScore;    public int lastTurnScore;    public String name;    public int chipPile;...

    Write Junit test for the following class below: public class Player {       public int turnScore;    public int roundScore;    public int lastTurnScore;    public String name;    public int chipPile;       public Player (String name) {        this.name = name;        this.turnScore = 0;        this.chipPile = 50;    }          public int getChip() {        return chipPile;    }       public void addChip(int chips) {        chipPile += chips;    }       public int getRoundScore() {        return roundScore;    }       public void setRoundScore(int points) {        roundScore += points;    }       public int getTurnScore() {        return turnScore;   ...

  • import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args)...

    import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args) { int[] grades = randomIntArr(10); printIntArray("grades", grades); ArrayList<Integer> indexesF_AL = selectIndexes_1(grades); System.out.println(" indexesF_AL: " + indexesF_AL); int[] indexesF_Arr = selectIndexes_2(grades); printIntArray("indexesF_Arr",indexesF_Arr); } public static int[] randomIntArr(int N){ int[] res = new int[N]; Random r = new Random(0); for(int i = 0; i < res.length; i++){ res[i] = r.nextInt(101); // r.nextInt(101) returns an in in range [0, 100] } return res; } public static void...

  • import java.util.ArrayList; import java.util.List; public abstract class AbstractBoxPacking { protected List input; protected int boxSize; public...

    import java.util.ArrayList; import java.util.List; public abstract class AbstractBoxPacking { protected List input; protected int boxSize; public AbstractBoxPacking(List input, int boxSize){ this.input = input; this.boxSize = boxSize; } public abstract int getOutput(); public List deepCopy(List boxes){ ArrayList copy = new ArrayList(); for(int i = 0; i < boxes.size(); i++){ copy.add(boxes.get(i).deepCopy()); } return copy; } } I need Help fixing the errors in my java code

  • import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private...

    import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private ArrayList<String> words; private HashSet<String> foundWords = new HashSet<String>(); public FindWordInMaze(char[][] grid) { this.grid = grid; this.words = new ArrayList<>();    // add dictionary words words.add("START"); words.add("NOTE"); words.add("SAND"); words.add("STONED");    Collections.sort(words); } public void findWords() { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[i].length; j++) { findWordsFromLocation(i, j); } }    for(String w: foundWords) { System.out.println(w); } } private boolean isValidIndex(int i, int j, boolean visited[][]) { return...

  • Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring;...

    Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring; public Person() {    this.numOffspring = 0; } public Person (int numOffspring) {    this.numOffspring = numOffspring; } public Person(String name, int birthYear, double weight, double height, char gender, int numCarryOn, int numOffspring) {    super(name, birthYear, weight, height, gender, numCarryOn);       if(numOffspring < 0) {        this.numOffspring = 0;    }    this.numOffspring = numOffspring; } public int getNumOffspring() {   ...

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */    public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...

  • I need some help with some homework questions. How would I implement the to-do's? ----------------------------------------------------------------------------------------------------------------------------------------------------------- AbstractArrayHea

    I need some help with some homework questions. How would I implement the to-do's? ----------------------------------------------------------------------------------------------------------------------------------------------------------- AbstractArrayHeap.Java package structures; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; public abstract class AbstractArrayHeap<P, V> {   protected final ArrayList<Entry<P, V>> heap;   protected final Comparator<P> comparator; protected AbstractArrayHeap(Comparator<P> comparator) {     if (comparator == null) {       throw new NullPointerException();     }     this.comparator = comparator;     heap = new ArrayList<Entry<P, V>>();   } public final AbstractArrayHeap<P, V> add(P priority, V value) {     if (priority == null || value...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT