K
K
Kentaro232018-04-24 12:53:42
Java
Kentaro23, 2018-04-24 12:53:42

How to test try/catch with JUNIT4?

Good afternoon! Idea highlights this piece as not covered with dough

} catch (Throwable e) {
                        System.out.println("An exception has occurred while trying to get logger. Stack trace: "
                                        + ExceptionUtils.getStackTrace(e));
                    }
I did the test, but idea still shows it as not covered by the test, here is a piece of the test, please help, maybe I'm doing it wrong
Assert.fail("An exception has occurred while trying to get logger. Stack trace: ");

        } catch (Throwable e) {
            assertTrue(e instanceof Throwable);
            System.out.println("An exception has occurred while trying to get logger. Stack trace: "
                    + ExceptionUtils.getStackTrace(e));
            Assert.assertNotEquals("", "An exception has occurred while trying to get logger. Stack trace: "
                    + ExceptionUtils.getStackTrace(e));

        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aol-nnov, 2018-04-24
@kentaro23

Monsieur, have you read the documentation for the Zhe-unit four?
https://junit.org/junit4/faq.html#atests_7

@Test(expected = MyMegaException.class)
public void testIfItBroke() {
    MyClass mega;
    mega.methodThatThrows(wrong params);
}

and, yes, I would use something more specific than Throwable.

Y
Yurii Nekrasov, 2018-05-03
@driversti

I hesitate to ask: why test this block of code? For the sake of 100% or so that the Idea does not highlight?
There is an opinion that you need to test business logic and slippery moments in particular.
Moreover, the error in your test example is that
ExceptionUtils.getStackTrace(e)
in the code and the test will most likely be different, so the test will fail. This is for the future

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question