JUnit Exception Testing

前端 未结 5 532
广开言路
广开言路 2020-12-14 19:54

Edit: Not JUnit 4 available at this time.

Hi there,

I have a question about \"smart\" exception testing with JUnit. At this time, I do it like this:

5条回答
  •  旧时难觅i
    2020-12-14 20:21

    With JUnit 4, you can use annotations instead. However, you should separate your test into 3 distinct methods for this to work cleanly. Note that IMHO catching an exception in the first scenario should be a failure, so I modified the catch block accordingly.

    public void testGet() {
        SoundFileManager sfm = new SoundFileManager();
    
        // Test adding a sound file and then getting it by id and name.
        try {
            SoundFile addedFile = sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            SoundFile sf = sfm.getSoundfile(addedFile.getID());
            assertTrue(sf!=null);
            System.out.println(sf.toString());
    
            sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            assertTrue(sf!=null);
            System.out.println(sf.toString());
        } catch (RapsManagerException e) {
            fail(e.getMessage());
        }
    }
    
    @Test(expected=RapsManagerException.class)
    public void testGetWithInvalidId() {
        SoundFileManager sfm = new SoundFileManager();
    
        sfm.getSoundfile(-100);
    }
    
    @Test(expected=RapsManagerException.class)
    public void testGetWithInvalidName() {
        SoundFileManager sfm = new SoundFileManager();
    
        sfm.getSoundfileByName(new String());
    }
    

提交回复
热议问题