简体   繁体   中英

Test argument of a void method with Mockito

Is it possible to test the values of an instance passed as an argument to a method that is void using Mockito?

public String foo() {
    Object o = new ObjectX();
    o.setField("hi");
    someDao.boo(o);
    return "response";
}

boo is void and I want to test that foo sets the field to "hi"

Updated this is what JB in my comments is suggesting.

@RunWith(MockitoJUnitRunner.class)
public class BarTest
{
    @Mock
    private SomeDao someDao;
    @InjectMocks
    private Bar     bar;

    @Before
    public void initMocks()
    {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFoo()
    {
        Mockito.doAnswer(new Answer<Object>()
        {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable
            {
                ObjectX x = (ObjectX) invocation.getArguments()[0];
                Assert.assertEquals("hi", x.getField());
                return null;
            }
        }).when(someDao).boo(Mockito.any(ObjectX.class));
        Assert.assertEquals("response", bar.foo());
    }
}

This below is my first answer and correct in its own way. No it's not possible with Mockito, since ObjectX is a new Object within the void method, to accomplish this with Mockito then you would have to pass ObjectX in as an argument to the method foo() . You might want to look into Powermock if your code can't be changed.

public String foo(ObjectX objectX) {
    Object o = objectX;
    o.setField("hi");
    someDao.boo(o);
    return "response";
}

Test case

@Test
public void testFoo()
{
    ObjectX mock = Mockito.mock(ObjectX.class);
    Assert.assertEquals("response", foo(mock));
    Mockito.verify(mock, Mockito.times(1)).setField(Mockito.eq("hi"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM