Unit Testing/JUnit/Test Exceptions

Create a Java Program

edit

Create the following Java program. Save it as Multiply.java

public class Multiply {
    public double multiply(double x, double y) {
        return x * y;
    }

    public String multiply(String string, int count) {
        if (count < 0) {
            throw new IllegalArgumentException(
                "count must greater than or equal to zero");
        }

        return string.repeat(count);
    }
}

Create a Test Program

edit

Create the following JUnit test program. Save it as Main.java

import org.junit.*;
import org.junit.runner.*;
import static org.junit.Assert.*;

public class Main {
    public static void main(String[] args) {
        org.junit.runner.JUnitCore.main("Main");
    }

    @Test
    public void multiply2x2Test() {
        Multiply multiply = new Multiply();
        double value = multiply.multiply(2, 2);
        org.junit.Assert.assertEquals(value, 4, 0.0);
    }

    @Test
    public void multiplyStringx2Test() {
        Multiply multiply = new Multiply();
        String value = multiply.multiply("test", 2);
        org.junit.Assert.assertEquals(value, "testtest");
    }

    @Test(expected = IllegalArgumentException.class)
    public void multiplyStringThrowsErrorTest() {
        Multiply multiply = new Multiply();
        String value = multiply.multiply("test", -1);
    }
}

Test Success

edit

Test the program by running it and observe the results.

Test Failure

edit

Change the multiply source code somehow, such as multiplying the string by a positive number. Test the program by running it again and observe the results.