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

你可能感兴趣的:(easymock)