Search code examples
javajunitconsolehamcrestprintln

Hamcrest - print to console


I'm testing a function called generateRandomByteInRange. It fails and I want to see the exact value it gets (and not only that it was less than -127). I tried to surround the assert with try - catch and when it fails to print to the console but nothing happened.

Function -

byte generateRandomByteInRange(int minVal,int maxVal) {
    Random rnd;
    rnd = new Random();
    return (byte) (rnd.nextInt(maxVal - minVal + 1) + minVal);
}

Test -

@Test
public void generateRandomByteInRange() {
    int res;
    int minVal,maxVal;

    minVal = 1;
    maxVal = 3;
    for (int i = 0; i < 100; i++) {
        res = AF.generateRandomByteInRange(minVal, maxVal);
        assertThat(res, is(both(greaterThanOrEqualTo(minVal)).and(lessThanOrEqualTo(maxVal))));
    }

    minVal = -127;
    maxVal = 128;
    for (int i = 0; i < 1000; i++) {
        res = AF.generateRandomByteInRange(minVal, maxVal);
        try {
            assertThat(res, is(both(greaterThanOrEqualTo(minVal)).and(lessThanOrEqualTo(maxVal))));
        } catch (Exception e) {
            System.out.println(res);
        }

    }
}

The test fails and I get the following message (in the right)

enter image description here


Solution

  • Hamcrest doesn't always do the greatest job in reporting back your value. If you take a closer look at the assertion message you got (bolding added for emphasis), you'd see that -128 is in fact the offending value. You can confirm this by changing res = AF.generateRandomByteInRange(minVal, maxVal) to some faulty hard-coded value (e.g., res = 400) and observe the assertion message.

    java.lang.AssertionError: Expected: is (a value equal to or greater than <-127> and a value less than or equal to <128>) but: a value equal to or greater than <-127> <-128> was less than <-127>

    Regarding your attempt to catch the exception - while somewhat redundant (see above), you had a good idea, but you caught the wrong exception. When an assertion fails, an AssertionError is thrown. This is an unchecked exception, and as such it extends java.lang.Error and not java.lang.Exception which you tried to catch. Just replace it with an explicit catch of AssertionError (or one of its base classes) and you should be OK.