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 {

	@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.
close
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors