EasyMock nice和Strict类型模拟

时间:2020-02-23 14:41:18  来源:igfitidea点击:

EasyMock模拟对象可以具有三种类型-默认,Strict和Nice。
我们可以在创建模拟对象时使用MockType枚举指定模拟对象类型。

EasyMock模拟类型

  • 默认值:仅预期录制的呼叫,但以任何顺序。
    如果跳过任何录制的通话,测试不会失败。

  • 严格(Strict):仅预期已录制的呼叫,并且录制的顺序相同。

  • Nice:期望以任何顺序记录通话,并为意外呼叫返回默认的空值(0,null,false)。

我们可以通过指定模拟类型来创建严格或者精美的模拟对象。

Object mock = mock(MockType.STRICT, Object.class);

Object mock1 = mock(MockType.NICE, Object.class);

如果使用@Mock批注,则可以通过以下任何一种方式指定模拟类型。

@Mock(MockType.STRICT)
Object obj;

@Mock(type=MockType.NICE)
Object obj1;

EasyMock严格的模拟示例

我们来看一个严格的模拟类型的简单示例。
我们将记录ArrayList模拟对象的一些行为,并以相同的顺序重播它们。

package com.theitroad.easymock;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.mock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;

import org.easymock.MockType;
import org.junit.jupiter.api.Test;

public class EasyMockStrictMockExample {

	@Test
	public void test() {
		ArrayList<Integer> mockList = mock(MockType.STRICT, ArrayList.class);
		expect(mockList.add(10)).andReturn(true);
		expect(mockList.add(20)).andReturn(true);
		expect(mockList.size()).andReturn(2);
		expect(mockList.get(0)).andReturn(10);
		replay(mockList);

		mockList.add(10);
		mockList.add(20);
		assertEquals(mockList.size(), 2);
		assertTrue(mockList.get(0) == 10);

		verify(mockList);
	}
}

如果在严格的模拟对象上调用了意外的方法,则错误消息将显示此时期望的方法调用,然后是第一个冲突的方法调用。

如果缺少调用,那么verify()方法错误消息将显示所有缺少的方法调用。

EasyMock Nice Mock示例

现在,让我们看一个漂亮的模拟示例。
我们将进行一些未记录的调用,并注意返回的值是方法返回类型的默认值。

package com.theitroad.easymock;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.mock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;

import java.util.ArrayList;

import org.easymock.Mock;
import org.easymock.MockType;
import org.junit.jupiter.api.Test;

public class EasyMockNiceMockExample {
	
	@Test
	public void test() {
		ArrayList<Integer> mockList = mock(MockType.NICE, ArrayList.class);
		expect(mockList.add(10)).andReturn(true);
		expect(mockList.size()).andReturn(2);
		expect(mockList.get(0)).andReturn(10);
		replay(mockList);

		mockList.add(10);
		//below will NOT throw exception because of nice mock
		boolean b = mockList.add(30);
		assertFalse(b);

		assertEquals(mockList.size(), 2);

		assertTrue(mockList.get(0) == 10);
		//verify won't throw error for unexpected calls for nice mock
		verify(mockList);
	}
}