EasyMock Mock Exceptions

Filed Under: EasyMock

EasyMock allows us to mock exceptions when a specific method is called. We can do this using andThrow() method along with expect().

EasyMock Mock Exception Example

Let’s say we have a following class.

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.

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 {

	public void test() {
		StringUtils mock = mock(StringUtils.class);
		expect(mock.toUpperCase(null)).andThrow(new IllegalArgumentException("NULL is not a valid argument"));
		IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> mock.toUpperCase(null));
		assertEquals("NULL is not a valid argument", exception.getMessage());

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content