EasyMock模拟异常
时间:2020-02-23 14:41:18 来源:igfitidea点击:
EasyMock允许我们在调用特定方法时模拟异常。
我们可以使用andThrow()方法和expect()来做到这一点。
EasyMock模拟异常示例
假设我们有以下程序。
package com.theitroad.utils;
public class StringUtils {
public String toUpperCase(String s) {
return s.toUpperCase();
}
}
这是模拟StringUtils对象,然后将其方法存根以抛出IllegalArgumentException的示例。
package com.theitroad.easymock;
import static org.easymock.EasyMock.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.theitroad.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);
}
}
我们正在使用JUnit 5断言来测试异常及其消息。

