mercredi 16 novembre 2016

EasyMock: andAnswer() vs andDelegateTo()

Which are differences between andAnswer() and andDelegateTo() methods in EasyMock in terms of usage?

First difference

I know that when andAnswer method is used, it is skipped the constructor call. This is important if the constructor makes extra things.

class Dummy{
    public Dummy(Object someArgument){
        // some validations of arguments
        System.out.println( "the constructor is called" );
    }
    public Object method(){
        System.out.println( "the method is called" );
        return new Object();
    }
}


@Test
public void testSt1() {
    Dummy mock = EasyMock.createMock( Dummy.class );
    EasyMock.expect( mock.method() ).andAnswer( new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            System.out.println( "mocked method is called" );
            return new Object();
        }
    } );

    EasyMock.replay( mock );
    mock.method();
}

@Test
public void testSt2() {
    Dummy mock = EasyMock.createMock( Dummy.class );
    EasyMock.expect( mock.method() ).andDelegateTo( new Dummy( new Dummy(new Object()) {
        @Override
        public Object method() {
            System.out.println( "mocked method is called" );
            return new Object();
        }
    } );

    EasyMock.replay( mock );
    mock.method();
}

Results:

  • testSt1() does not call the constructor of Dummy
  • testSt2() calls the constructor of Dummy

What are the other differences?

Aucun commentaire:

Enregistrer un commentaire