jUnit same exception in different cases

前端 未结 2 2021
-上瘾入骨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:32

    If you have JUnit 4.7 or above you can use this (elegant) way:

    @Rule
    public ExpectedException exception = ExpectedException.none();
    
    @Test
    public void testRodneCisloRok(){
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("error1");
        new RodneCislo("891415",dopocitej("891415"));
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题