Skip to content

Instantly share code, notes, and snippets.

@mariuszs
Last active March 19, 2024 10:08
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mariuszs/7489190 to your computer and use it in GitHub Desktop.
Save mariuszs/7489190 to your computer and use it in GitHub Desktop.
Mockito + Catch Exception + AssertJ - BDD Style!
import com.googlecode.catchexception.MyException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static com.googlecode.catchexception.apis.BDDCatchException.caughtException;
import static com.googlecode.catchexception.apis.BDDCatchException.when;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private OtherService otherServiceMock;
@InjectMocks
private MyService myService;
@Test
public void testDoThat() {
given(otherServiceMock.bar()).willThrow(new MyException());
when(() -> myService.foo());
then(caughtException()).isInstanceOf(MyException.class);
}
}
@frankhenderson
Copy link

Does this support when(someOtherObject).doSomethingWhichCallsMyMockDoSomething(); ? Or are exceptions only caught on the object given to when() ?

@brobert83
Copy link

How can you do the same thing but with a void method?

@eneveu
Copy link

eneveu commented Jul 11, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment