1

I am currently testing a method, let me call it testedMethod().

The body of the method looks like this

private testedMethod(List<Protocoll> protocolList) {
    //so something with the protocolList
    if (something) && (somethingElse) {
        Assert.isFalse(areTheProtocollsCorrect(p1, p2), "Error, the protocols are wrong");
    }

    if (somethingCompeletlyElse) && (somethingElse) {
        Assert.isFalse(areTheProtocollsExactlyTheSame(p1, p2), "Error, the protocols are the same");
    }
}

Additional code from the Assert.class:

isFalse:

public static void isFalse(boolean condition, String descr) {
    isTrue(!condition, descr);
}

isTrue:

public static void isTrue(boolean condition, String descr) {
    if (!condition) {
        fail(descr);
    }
}

fail:

public static void fail(String descr) {
    LOGGER.fatal("Assertion failed: " + descr);
    throw new AssertException(descr);
}

Testing what the method should do correctly is allready done. But I would like to test those assertions. This assertions are an important part of the code, and I would like to see if the method is throwing those errors when I provide wrong data to it. How can I do it using JUnit?

hc0re
  • 1,806
  • 2
  • 26
  • 61

1 Answers1

1

In the first place, I you are currently using JUnit, you shouldn't code your own assert* or fail methods: They are already included in the Assert class.

Anyway, if you want to test your assertions, you have to code two kind of test cases: positive cases and negative (failing) cases:

@Test
public void positiveCase1()
{
    // Fill your input parameters with data that you know must work:
    List<Protocoll> protocolList=...
    testedMethod(protocolList);
}

@Test
public void positiveCase2()
{
    ...
}

@Test(expected=AssertException.class)
public void negativeCase1()
{
    // Fill your input parameters with data that you know must NOT work:
    List<Protocoll> protocolList=...
    testedMethod(protocolList);
}

@Test(expected=AssertException.class)
public void negativeCase2()
{
    ...
}

The expected parameter in the Test annotation makes JUnit check that an exception of that type was raised. Else, the test is marked as failed.

But I still insist in that it's better to use the JUnit standards.

Little Santi
  • 8,563
  • 2
  • 18
  • 46
  • Thanks for the answer, still, I am using the JUnit assertions. The other assertions in my code have completely other purpose and they are not used in JUnit tests :) – hc0re Nov 12 '15 at 21:31
  • OK. In that case, my answer will fit for your case. – Little Santi Nov 12 '15 at 21:34