Search code examples
javamockitojunit5spring-boot-test

How to mock using Mockito and assert a thrown exception and message using Junit5?


I am using Mockito along with Junit5 as well as SpringBootTest. I need to assert a thrown exception as well as its message.


Solution

  • import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.function.Executable;
    
    
    @SpringBootTest
    class Sample{
    
       @Autowired
       TestService service;
    
       @Test
       void sampleTest(){
          Executable exec = ()-> service.execute();
          Throwable thrown = assertThrows(MyException.class, exec, "Type your message");        
          assertEquals("Dancing stars", thrown.getMessage());
        }
    }
    

    Please refer doc here.