Jump to content

Unit Testing/JUnit/Create a Simple Test

From Wikiversity

Create a Java Program

[edit | edit source]

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

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

Create a Test Program

[edit | edit source]

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 Success

[edit | edit source]

Test the program by running it and observe the results.

Test Failure

[edit | edit source]

Change the multiply source code somehow, such as multiplying by 0 rather than multiplying by y. Test the program by running it again and observe the results.