Java – exception in JUnit interrupt
                                        
                    •
                    Java                                    
                See English answers > JUnit exception testing 5
For example The testappleissweetandred test calls the following –
testAppleisSweetAndRed(orange,red,sweet)//throws exception testAppleisSweetAndRed(apple,green,sour)//throws exception testAppleisSweetAndRed(apple,sweet)//OK
If the behavior of the call is as expected, the test succeeds How do assertions catch the first three calls to ensure that they do throw the expected exception?
Solution
If you are using JUnit 4 or later, you can execute as follows You can use
@Rule public ExpectedException exceptions = ExpectedException.none();
This provides many features that can be used to improve JUnit testing If you see the following example, I'll test three things on exceptions
>Type of exception thrown > exception message > reason of exception
public class MyTest {
    @Rule
    public ExpectedException exceptions = ExpectedException.none();
    ClassUnderTest testClass;
    @Before
    public void setUp() throws Exception {
        testClass = new ClassUndertest();
    }
    @Test
    public void testAppleisSweetAndRed() throws Exception {
        exceptions.expect(Exception.class);
        exceptions.expectMessage("this is the exception message");
        exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));
        testClass.appleisSweetAndRed(orange,sweet);
    }
}
                
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        