`

Learning EasyMock3.0 By Official Example

 
阅读更多
Maven Installation+
add following code to pom.xml
<dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <version>3.0</version>
      <scope>test</scope>
    </dependency>


EasyMock Basic Flow
引用
1 create Mock object by EasyMock;
 SomeInterface mockObj = createMock(SomeInterface.class);  

or
引用
IMocksControl control = createControl();
SomeInterface mockObj = control.createMock(SomeInterface.class);
AnotherInterface mockAnotherObj = control.createMock(AnotherInterface.class);



    2 set the expected behavior and Return Results;
expect(mockObj.someAction(1)).andReturn("one");

    3 Switch the esaymock to replay state;
replay(mockObj); 

or
control.replay();


    4 do unit test with mock object;

    5 verify
verify(mockObj);



Usage
The following examples use the interface Collaborator:
package org.easymock.samples;

public interface Collaborator {
    void documentAdded(String title);
    void documentChanged(String title);
    void documentRemoved(String title);
    byte voteForRemoval(String title);
    byte[] voteForRemovals(String[] title);
}


Implementors of this interface are collaborators (in this case listeners) of a class named ClassUnderTest:
package org.easymock.samples;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ClassTested {

    private final Set<Collaborator> listeners = new HashSet<Collaborator>();

    private final Map<String, byte[]> documents = new HashMap<String, byte[]>();

    public void addListener(final Collaborator listener) {
        listeners.add(listener);
    }

    public void addDocument(final String title, final byte[] document) {
        final boolean documentChange = documents.containsKey(title);
        documents.put(title, document);
        if (documentChange) {
            notifyListenersDocumentChanged(title);
        } else {
            notifyListenersDocumentAdded(title);
        }
    }

    public boolean removeDocument(final String title) {
        if (!documents.containsKey(title)) {

            return true;
        }

        if (!listenersAllowRemoval(title)) {
            return false;
        }

        documents.remove(title);
        notifyListenersDocumentRemoved(title);

        return true;
    }

    public boolean removeDocuments(final String... titles) {
        if (!listenersAllowRemovals(titles)) {
            return false;
        }

        for (final String title : titles) {
            documents.remove(title);
            notifyListenersDocumentRemoved(title);
        }
        return true;
    }

    private void notifyListenersDocumentAdded(final String title) {
        for (final Collaborator listener : listeners) {
            listener.documentAdded(title);
        }
    }

    private void notifyListenersDocumentChanged(final String title) {
        for (final Collaborator listener : listeners) {
            listener.documentChanged(title);
        }
    }

    private void notifyListenersDocumentRemoved(final String title) {
        for (final Collaborator listener : listeners) {
            listener.documentRemoved(title);
        }
    }

    private boolean listenersAllowRemoval(final String title) {
        int result = 0;
        for (final Collaborator listener : listeners) {
            result += listener.voteForRemoval(title);
        }
        return result > 0;
    }

    private boolean listenersAllowRemovals(final String... titles) {
        int result = 0;
        for (final Collaborator listener : listeners) {
            result += listener.voteForRemovals(titles);
        }
        return result > 0;
    }

}



package org.easymock.samples;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;

public class ExampleTest {

	private ClassTested classUnderTest;

	private Collaborator mock;

	@Before
	public void setup() {
		mock = createMock(Collaborator.class);
		classUnderTest = new ClassTested();
		classUnderTest.addListener(mock);
	}

	@Test
	public void removeNonExistingDocument() {
		replay(mock);
		classUnderTest.removeDocument("Does not exist");
	}

	@Test
	public void addDocument() {
		mock.documentAdded("New Document");
		replay(mock);
		classUnderTest.addDocument("New Document", new byte[0]);
		verify(mock);
	}

	@Test
	public void addAndChangeDocument() {
		mock.documentAdded("Document");
		mock.documentChanged("Document");
		expectLastCall().times(3);
		replay(mock);
		classUnderTest.addDocument("Document", new byte[0]);
		classUnderTest.addDocument("Document", new byte[0]);
		classUnderTest.addDocument("Document", new byte[0]);
		classUnderTest.addDocument("Document", new byte[0]);
		verify(mock);
	}

	@Test
	public void voteForRemoval() {
		// expect document addition
		mock.documentAdded("Document");
		// expect to be asked to vote, and vote for it
		expect(mock.voteForRemoval("Document")).andReturn((byte) 42);
		// expect document removal
		mock.documentRemoved("Document");

		replay(mock);
		classUnderTest.addDocument("Document", new byte[0]);
		assertTrue(classUnderTest.removeDocument("Document"));
		verify(mock);
	}

	@Test
	public void voteAgainstRemoval() {
		// expect document addition
		mock.documentAdded("Document");
		// expect to be asked to vote, and vote against it
		expect(mock.voteForRemoval("Document")).andReturn((byte) -42); //
		// document removal is *not* expected

		replay(mock);
		classUnderTest.addDocument("Document", new byte[0]);
		assertFalse(classUnderTest.removeDocument("Document"));
		verify(mock);
	}

	@Test
	public void voteForRemovals() {
		mock.documentAdded("Document 1");
		mock.documentAdded("Document 2");
		expect(mock.voteForRemovals("Document 1", "Document 2")).andReturn(
				(byte) 42);
		mock.documentRemoved("Document 1");
		mock.documentRemoved("Document 2");
		replay(mock);
		classUnderTest.addDocument("Document 1", new byte[0]);
		classUnderTest.addDocument("Document 2", new byte[0]);
		assertTrue(classUnderTest.removeDocuments(new String[] { "Document 1",
				"Document 2" }));
		verify(mock);
	}

	@Test
	public void voteAgainstRemovals() {
		mock.documentAdded("Document 1");
		mock.documentAdded("Document 2");
		expect(mock.voteForRemovals("Document 1", "Document 2")).andReturn(
				(byte) -42);
		replay(mock);
		classUnderTest.addDocument("Document 1", new byte[0]);
		classUnderTest.addDocument("Document 2", new byte[0]);
		assertFalse(classUnderTest.removeDocuments("Document 1", "Document 2"));
		verify(mock);
	}

	@SuppressWarnings("unchecked")
	@Test
	public void answerVsDelegate() {
		final List<String> l = createMock(List.class);

		// andAnswer style
		expect(l.remove(10)).andAnswer(new IAnswer<String>() {
			public String answer() throws Throwable {
				return getCurrentArguments()[0].toString();
			}
		});

		// andDelegateTo style
		expect(	l.remove(10)).
				andDelegateTo
					(
							new ArrayList<String>() {
								private static final long serialVersionUID = 1L;

								@Override
								public String remove(final int index) {
									return Integer.toString(index);
								}
							}
				);

		replay(l);

		assertEquals("10", l.remove(10));
		assertEquals("10", l.remove(10));

		verify(l);
	}
}


Official quick start
http://easymock.org/EasyMock3_0_Documentation.html

EasyMock3.0 API
http://easymock.org/api/easymock/3.0/index.html
分享到:
评论

相关推荐

    jmock2.5.1和easymock3.0

    本资源包含JMock 2.5.1和EasyMock 3.0的库文件,使得开发者在进行单元测试时无需再四处寻找相关依赖。 **JMock 2.5.1** JMock是一个强大的模拟框架,它允许开发者创建和控制模拟对象,这些对象可以在测试中替代真实...

    junit4.4.jar +easymock3.0.jar

    标题中的"junit4.4.jar +easymock3.0.jar"提及了两个重要的Java测试库:JUnit 4.4和EasyMock 3.0。这些是用于开发过程中的单元测试的关键工具。 JUnit是Java编程语言中最广泛使用的单元测试框架之一。它允许开发者...

    easyMock3.0

    有用的jar包 是我好不容易找到的 现在分享给大家了

    easymock 3.0

    Easymock 3.0 是一个流行的Java模拟框架,用于进行单元测试。它使得开发者能够在测试代码中创建和控制对象的行为,以便于隔离被测试代码并确保其正确性。在单元测试中,Easymock允许我们创建mock对象,这些对象模仿...

    easymock-3.0.jar

    java运行依赖jar包

    easymockclassextension-3.0.jar

    easymockclassextension-3.0.jar org.easymock.classextension.EasyMock.

    easymock.jar,easymockclassextension.jar

    Easymock是一个流行的Java单元测试框架,它允许开发者创建模拟对象来测试代码。这个框架使得测试更加简单,因为你可以模拟任何复杂的交互和行为,而无需实际运行依赖的组件。在给定的压缩包文件中,包含两个核心的...

    easymock-3.0-sources.jar

    jar包,官方版本,自测可用

    easymock-3.0-samples.jar

    jar包,官方版本,自测可用

    easymock-3.0.jar中文-英文对照文档.zip

    注:下文中的 *** 代表文件名中的组件名称。 # 包含: 中文-英文对照文档:【***-javadoc-API文档-中文(简体)-英语-对照版.zip】 jar包下载地址:【***.jar下载地址(官方地址+国内镜像地址).txt】 ...

    EasyMock入门

    在提供的`easymock.rar`和`easymock-3.0.zip`文件中,可能包含了EasyMock的库文件和相关的示例代码。你可以解压并导入到你的项目中,参考示例来学习和使用EasyMock。在实际应用中,结合IDE(如Eclipse或IntelliJ ...

    EasyMock

    EasyMock 是一个强大的Java模拟框架,它允许开发者在单元测试中创建和控制对象的行为,以模拟复杂的交互场景。这个框架的出现,极大地简化了对那些难以或无法直接实例化的类的测试,比如接口或者静态方法。EasyMock...

    easyMock

    EasyMock 是一个强大的Java模拟框架,它允许开发者在单元测试中创建和控制对象的行为,以模拟复杂的依赖关系。这个框架的出现使得测试更加简洁、独立,可以有效地验证代码的正确性,而无需运行实际的依赖服务或库。...

    easymockclassextension-3.0-sources.jar

    jar包,官方版本,自测可用

    easymock-3.2.zip

    EasyMock 3.2 是一个流行的开源Java模拟框架,它为开发者提供了强大的单元测试支持。在Java开发中,单元测试是验证代码独立模块正确性的关键步骤。EasyMock可以帮助程序员模拟对象的行为,使得测试过程更加可控,...

    easymock-3.2.jar

    EasyMock主要是为测试提供模拟数据,比如你可以模拟HttpServletRequest。

    EasyMock介绍和使用

    【EasyMock介绍】 EasyMock是一款强大的Java模拟框架,它允许开发者在进行单元测试时创建和控制对象的行为。这个工具使得测试更加独立,可以隔离被测试代码与其他依赖的系统,从而提高测试的效率和质量。EasyMock的...

Global site tag (gtag.js) - Google Analytics