Last active
March 19, 2024 10:08
-
-
Save mariuszs/7489190 to your computer and use it in GitHub Desktop.
Mockito + Catch Exception + AssertJ - BDD Style!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
How can you do the same thing but with a void method?
@brobert83 : for void methods, you should write doThrow(new MyException()).when(otherServiceMock).bar()
.
More information here:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this support when(someOtherObject).doSomethingWhichCallsMyMockDoSomething(); ? Or are exceptions only caught on the object given to when() ?