问题
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 ofDummy
testSt2()
calls the constructor ofDummy
What are the other differences?
回答1:
The purpose of the two methods is to provide different levels of responsibility for your tests. Your example isn't that great, though.
Here's a simple method that demonstrates how functionally these two provide different test expectations.
public String foo() throws Exception {
throw new Exception();
}
With andAnswer
, you can make a mocked version of this method return a String, even though it would never return one in practice. Your use of andAnswer
implies an expected response.
With andDelegateTo
, this will always throw an Exception. Your use of andDelegateTo
implies an actual response.
andAnswer
means your test-specific code will handle the response. For example, if you create a ParrotAnswer for a MockDao update
method, the Parrot will return the updated Object, but no Dao is actually instantiated in the process. This is nice for unit testing where you basically walk the test subject through, but doesn't help if your mocked method doesn't do as what you method actually does.
andDelegateTo
allows you to provide an actual Object implementing the interface to handle the response. We're allowing our test subject controlled access to a resource, rather than providing unrestricted access to a full resource. benefit of this is that you can test integration into a test environment, but minimize actual changes to the test environment. For example, you can delegate get
to a wired Dao to fetch an actual live value from the Db, and mock the delete
method, so you don't actually delete that same value during testing (and having to recreate it again later to do the same test if it has a static id, for example).
来源:https://stackoverflow.com/questions/40640742/easymock-andanswer-vs-anddelegateto