简体   繁体   中英

Mockito: difference between thenThrow(Exception.class) and thenThrow(new Exception())

I'm using Mockito for the first time and I was wondering what the difference is between using when(dao.create(order)).thenThrow(new SQLException()); and when(dao.create(order)).thenThrow(SQLException.class); . Both seem to run just fine and I can't find anything about it in the Mockito API .

The only difference I can think of, is that when using new SQLException() you can enter arguments in the constructor. Is this it?

when(dao.create(order)).thenThrow(new SQLException()); 

This will throw the exception object provided by you. For instance, you can create an exception with specific parameters such as new SQLException("description of exception", "sql:code")

when(dao.create(order)).thenThrow(SQLException.class); 

This will create a default instance of the specified class using reflection.

thenThrow can take a throwable as its argument. You shouldn't monitor for throwable as this means the logic can also catch Error which is something usually non recoverable.

Passing new SQLException() is equivalent to SQLException.class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM