Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

frankhenderson commented Aug 7, 2014

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

@brobert83
Copy link

brobert83 commented Jul 7, 2015

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