problems using fail in junit

Asked

Viewed 47 times

0

I want to create custom message for every exception error in my test class, my test is working perfectly, however when I purposely make a mistake it does not come within my exception as you can see below;

try {
    error.checkThat(tipoIndicioService.getPorId(1), is(tipoIndicio));
} catch (Exception e) {
    e.printStackTrace();
    Assert.fail("O valor do tipo indicio que está no arquivo CSV não existe no banco de dados");
}

I initiated her through the ErrorCollector as shown below;

@Rule
public ErrorCollector error = new ErrorCollector();

how do I fall into the exception?

1 answer

2


1 - To accomplish what you want, just pass the message on checkThat thus:

error.checkThat("O valor do tipo indicio que está no arquivo CSV não existe no banco de dados", tipoIndicioService.getPorId(1), is(tipoIndicio));

The first parameter is precisely the reason for the failure. You do not need to do this control manually.

2 - The asserts do not throw an exception when they fail, they throw an Error. To fall in the catch you have to do this:

catch (Error e) {
    e.printStackTrace();
    Assert.fail("O valor do tipo indicio que está no arquivo CSV não existe no banco de dados");
}

The fact that you can do it doesn’t mean you should. In your case I don’t think you need.

3 - Lastly, in your specific case, even if you put the catch(Error), the error will not fall on catch because the checkThat does not throw this error. The idea of this ErrorCollector is just continue the test even after a failure is found.

If you run the code below, where we are not using the ErrorCollector, will realize that the "Test" message will not be displayed and the error will be captured in the catch:

try {
    Assert.fail();
    System.out.println("Test");
} catch (Error e) {
    System.out.println("O valor do tipo indicio que está no arquivo CSV não existe no banco de dados");
}

Already in the following code, we are using the ErrorCollector. In this case, even if the test fails, the flow continues and the "Test" message will be displayed. However, the error will not be captured in catch, because the checkThat not the spear.

try {
    error.checkThat(1, is(2));
    System.out.println("Test");
} catch (Error e) {
    System.out.println("O valor do tipo indicio que está no arquivo CSV não existe no banco de dados");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.