Reputation: 713
I'm writing a junit test for a particular method. The method contains calls to other methods in a DAO class which I am mocking with EasyMock.
I want to assert that one of these DAO class methods is called once, which is what I assume expectLastCall().once() is for. The method in question returns void.
The test I have currently passes, I just want to make sure my logic is correct as I haven't used EasyMock before. I used this question as a reference: EasyMock expectations with void methods
So, here is the code:
@Before
public void setUp() throws Exception{
this.fooService = new FooService();
this.fooMock = createStrictMock(FooDAO.class);
}
@Test
public void test_fooTest(){
String arg1 = "arg1";
String arg2 = "arg2";
this.fooService.setFooDAO(fooMock);
expect(this.fooMock.someMethod(arg1, arg2)).andReturn(something);
fooMock.methodThatShouldBeCalledOnce(EasyMock.<Object>anyObject());
EasyMock.expectLastCall().once();
replay(this.fooMock);
this.fooService.methodUnderTest(someArg, someArg2);
verify(this.fooMock);
}
What I think this does is assert that there is a call to methodThatShouldBeCalledOnce and that it only happens once. I don't really care about someMethod but of course EasyMock complains if it's not told to expect it.
Thank you!
Upvotes: 2
Views: 21373
Reputation: 5721
If you don't care about some methods, you should create a nice mock. Then, indeed, there's no need to call expectLastCall. It is implicit but can be a good practice to make it obvious you are mocking a method. once() is also not needed since it is the default.
So, if a rephrase it, using a nice mick, removing implicit calls, adding static imports and not adding redundant "this", you should get:
@Before
public void setUp() throws Exception{
fooService = new FooService();
fooMock = createNiceMock(FooDAO.class);
fooService.setFooDAO(fooMock);
}
@Test
public void test_fooTest(){
fooMock.methodThatShouldBeCalledOnce(anyObject());
replay(fooMock); // or replayAll() if you extend EasyMockSupport
fooService.methodUnderTest(someArg, someArg2);
verify(fooMock); // or verifyAll() if you extend EasyMockSupport
}
Upvotes: 1
Reputation: 691715
That looks correct to me. You could easily check by yourself by removing the call to the void method and verify that the test fails, or by adding a second call to the void method and see that the test also fails.
Upvotes: 1