jUnit same exception in different cases

前端 未结 2 2025
-上瘾入骨i
-上瘾入骨i 2021-02-05 23:08

I\'m writing a jUnit test for a constructor that parses a String and then check numerous things. When there\'s wrong data, for every thing, some IllegalArgumentException with di

2条回答
  •  一向
    一向 (楼主)
    2021-02-05 23:39

    You'll need to do it the old fashioned way:

    @Test
    public void testRodneCisloRok() {
        try {
           new RodneCislo("891415",dopocitej("891415"));
           fail("expected an exception");
        } catch (IllegalArgumentException ex) {
           assertEquals("error1", ex.getMessage());
        }
    }
    

    The @Test(expected=...) syntax is a handy convenience, but it's too simple in many cases.

    If it is important to distinguish between exception conditions, you might want to consider developing a class hierarchy of exceptions, that can be caught specifically. In this case, a subclass of IllegalArgumentException might be a good idea. It's arguably better design, and your test can catch that specific exception type.

提交回复
热议问题