1.3. Unit Testing
LongInteger: unit tests.
Test: LongInteger()
LongInteger()Let us create a testing class called LongIntegerTest and make a unit test for the constructors:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class LongIntegerTest {
@Test
public void testConstructors() {
// default constructor
assertEquals("0", new LongInteger().toString());
// constructor with a string parameter
assertEquals("12", new LongInteger("12").toString());
assertEquals("34", new LongInteger("+34").toString());
assertEquals("-56", new LongInteger("-56").toString());
assertEquals("-0", new LongInteger("-0").toString());
// copy constructor
assertEquals("12", new LongInteger(new LongInteger("12")).toString());
assertEquals("-34", new LongInteger(new LongInteger("-34")).toString());
}
}L6: the@Testannotation indicates that this method is used for unit testing.L7: methods used for unit testing must bepublic.L8: tests the default constructorassertEquals(): compares two parameters where the left parameter is the expected value and the right parameter is the actual value.
L12-15: tests the constructor with a string parameter.L18-19: tests the copy constructor.
When should we use
import staticinstead ofimport?
When you run this test, you see a prompt similar to the followings:
Tests passed: 1 of 1 testTest: multiply()
multiply()Let us define another method for testing the multiply() method:
@Test
public void testMultiply() {
LongInteger a = new LongInteger("123456789");
a.multiply(new LongInteger("1"));
assertEquals("123456789", a.toString());
a.multiply(new LongInteger("-1"));
assertEquals("-123456789", a.toString());
a.multiply(new LongInteger("-1234567890123456789"));
assertEquals("152415787517146788750190521", a.toString());
a.multiply(new LongInteger("0"));
assertEquals("0", a.toString());
a.multiply(new LongInteger("-0"));
assertEquals("-0", a.toString());
}L11-12:acan hold the integer152415787517146788750190521(), which is much larger than the maximum value oflongthat is .
Test: compareTo()
compareTo()Let us define a method for testing the compareTo() method:
@Test
public void testCompareTo() {
assertTrue(0 < new LongInteger("0").compareTo(new LongInteger("-0")));
assertTrue(0 > new LongInteger("-0").compareTo(new LongInteger("0")));
assertTrue(0 < new LongInteger("12").compareTo(new LongInteger("-34")));
assertTrue(0 > new LongInteger("-12").compareTo(new LongInteger("34")));
assertTrue(0 > new LongInteger("-34").compareTo(new LongInteger("12")));
assertTrue(0 < new LongInteger("34").compareTo(new LongInteger("-12")));
}assertTrue(): passes if the parameter returns true.
Last updated
Was this helpful?