I discovered Mockito[1] in some other code that I was using, and it 
seems to be easier to use than JMock:

Set-up (and it can mock classes, too, not just interfaces):
        container = mock(DomainObjectContainer.class);

Governing behaviour:
        
when(container.newTransientInstance(Promotion.class)).thenReturn(containedPromotion);
        
when(container.newTransientInstance(Member.class)).thenReturn(containedMember);

Checking behaviour:
        verify(container).persistIfNotAlready(member);

Other interactions can be detected with:
        verifyNoMoreInteractions(container);


>From the javadoc:
   verify(mock).someMethod("some arg");
Above is equivalent to:
   verify(mock, times(1)).someMethod("some arg");

An entire test looks like:

    @Before
    public void setup() {
        container = mock(DomainObjectContainer.class);
        authentication = mock(Authentication.class);

        repository = new MemberRepositoryDefault();
        repository.setContainer(container);
        repository.setAuthentication(authentication);

        containedMember = new Member();
        containedMember.setAddress("contained");
        containedMember.setContainer(container);
        containedMember.setAuthentication(authentication);
        containedMember.setMembers(repository);

        
when(container.newTransientInstance(Member.class)).thenReturn(containedMember);
    }


    @SuppressWarnings("unchecked")
    @Test
    public void ensureThatNewMemberHasApplicantStatus() {
        when(authentication.memberExists(any(String.class))).thenReturn(false);
        Member member = repository.newMember("Another Test", "Member", 
"email@domain");
        assertNotNull(member);
        verify(container).persistIfNotAlready(member);
        verify(authentication).memberExists("atmember");
        verify(container).newTransientInstance(Member.class);
        verify(container, 
atLeastOnce()).newPersistentInstance((Class<AbstractDomainObject>) anyObject());
        verifyNoMoreInteractions(container);
        assertThat(member.getMemberLevel(), 
is(equalTo(MemberLevel.MEMBER_APPLICANT)));
        assertThat(member.getState(), is(equalTo(State.NEW)));

        ongoingMember = member;
    }



I found this easier to use than setting up a Mockery context..


Anyone have any other experiences?

Add to pom.xml:
<dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.9.0-rc1</version>
      <scope>test</scope>
</dependency>


[1] http://code.google.com/p/mockito/
http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html


Reply via email to