-3

I have an assingment that require me to test if a matrix meets a certain requirement, which I have completed, and then test it in a JUnit test, which I don't know how. I have created the folder for the JUnit test but I don't know how to write the test. So far I did the test in the main class.

public static void main(String[] args) {
    int matrix[][] = {{2,7,6},{9,5,1},{4,3,8}};

    System.out.println(isMagicSquare(matrix));

    // changing one element
    matrix[0][2] = 5;
    System.out.println(isMagicSquare(matrix));
}

public static boolean isMagicSquare(int[][] matrix) {
    // actual code omitted for the sake of simplicity.
}
glee8e
  • 6,180
  • 4
  • 31
  • 51
none
  • 33
  • 1
  • 3
  • Have you looked at examples of JUnit tests on the JUnit web site? – Dawood ibn Kareem Jun 05 '17 at 00:47
  • Yea I tried but I couldn't find something helpful – none Jun 05 '17 at 00:55
  • 1
    In general, you would create another class (e.g., `TestMagicSquare`), and use annotations to mark the methods that will invoke tests (e.g., `testValidSquare()` and `testInvalidSquare()`), write the methods appropriately, and then invoke it with the JUnit system. If you are using Eclipse or another IDE, things are somewhat simplified for running the tests. – KevinO Jun 05 '17 at 02:31

1 Answers1

0

First you create the class that you want to test.

public class MagicSquare
{
    private int[][] matrix;

    public MagicSquare(int[][] matrix)
    {
        this.matrix = matrix;
    }

    public boolean isValid()
    {
        // validation logic
    }
}

Then you create the test class.

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class MagicSquareTest
{
    @Test
    public void testMagicSquare1()
    {
        int[][] matrix = { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is a valid magic square
        assertTrue(square.isValid());
    }

    @Test
    public void testMagicSquare2()
    {
        int[][] matrix = { { 2, 7, 5 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is an invalid magic square
        assertFalse(square.isValid());
    }
}

Finally see the answers to this question on how to run the test cases from the command line.

petejdev
  • 16
  • 2