EasyMock Mock Exception Example
Let’s say we have a following class.
1 2 3 4 5 6 7 8 |
package com.journaldev.utils; public class StringUtils { public String toUpperCase(String s) { return s.toUpperCase(); } } |
Here is the example of mocking StringUtils
object and then stub its method to throw IllegalArgumentException
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.journaldev.easymock; import static org.easymock.EasyMock.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import com.journaldev.utils.StringUtils; public class EasyMockExceptionExample { @Test public void test() { StringUtils mock = mock(StringUtils.class); expect(mock.toUpperCase(null)).andThrow(new IllegalArgumentException("NULL is not a valid argument")); replay(mock); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> mock.toUpperCase(null)); assertEquals("NULL is not a valid argument", exception.getMessage()); verify(mock); } } |
We are using JUnit 5 Assertions to test exception and its message.
You can checkout complete project and more EasyMock examples from our GitHub Repository.