Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile error while using EasyMock.expect() in very simple example?

I am trying a very simple example using EasyMock, however I simply cannot make it build. I have the following test case:

@Test
public void testSomething()
{
    SomeInterface mock = EasyMock.createMock(SomeInterface.class);
    SomeBase expected = new DerivesFromSomeBase();

    EasyMock.expect(mock.send(expected));
}

However I get the following error in the EasyMock.expect(... line:

The method expect(T) in the type EasyMock is not applicable for the arguments (void)

Can somebody point me in the correct direction? I am completely lost.

like image 483
Bjarke Freund-Hansen Avatar asked Aug 26 '11 12:08

Bjarke Freund-Hansen


People also ask

What does EasyMock expect do?

The expect() method tells EasyMock to simulate a method with certain arguments. The andReturn() method defines the return value of this method for the specified method parameters. The times() method defines how often the Mock object will be called. The replay() method is called to make the Mock object available.

How do you expect a void method to call in EasyMock?

andVoid() If we just want to mock void method and don't want to perform any logic, we can simply use expectLastCall(). andVoid() right after calling void method on mocked object. You can checkout complete project and more EasyMock examples from our GitHub Repository.


2 Answers

If you want to test void methods, call the method you want to test on your mock. Then call the expectLastCall() method.

Here's an example:

@Test
public void testSomething()
{
    SomeInterface mock = EasyMock.createMock(SomeInterface.class);
    SomeBase expected = new DerivesFromSomeBase();

    mock.send(expected);

    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() {
            // do additional assertions here
            SomeBase arg1 = (SomeBase) EasyMock.getCurrentArguments()[0];

            // return null because of void
            return null;
        }
    });
}
like image 52
Jasper Avatar answered Oct 05 '22 23:10

Jasper


Since your send() method returns void, just call the mock method with expected values and replay:

SomeInterface mock = EasyMock.createMock(SomeInterface.class);
SomeBase expected = new DerivesFromSomeBase(); 
mock.send(expected);
replay(mock);
like image 26
Biju Kunjummen Avatar answered Oct 06 '22 01:10

Biju Kunjummen