首页 > 解决方案 > TooLittleActualInvocations:

问题描述

I try to use mock to verify method for serveral times.But I meet this problem.

org.mockito.exceptions.verification.TooLittleActualInvocations: 
personDao.update(isA(com.zhaolu08.Person));
Wanted 3 times:
-> at com.zhaolu08.PersonServiceTest.testUpdate(PersonServiceTest.java:32)
But was 1 time:

while my code is:

package com.zhaolu08;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.isA;
import static org.mockito.Mockito.eq;
public class PersonServiceTest {
    private PersonDao mockDao;
    private PersonService personService;

    @Before
    public void setUp() throws Exception {
        //模拟PersonDao对象
        mockDao = mock(PersonDao.class);
        when(mockDao.getPerson(1)).thenReturn(new Person(1, "Person1"));
        when(mockDao.update(isA(Person.class))).thenReturn(true);
        personService = new PersonService(mockDao);
    }

    @Test
    public void testUpdate() throws Exception {

        boolean result = personService.update(1, "new name");
        Assert.assertTrue("must true", result);
        verify(mockDao, times(2)).getPerson(eq(1));
        verify(mockDao, times(3)).update(isA(Person.class));

    }
}

I can't find out the problem. I try some methods. They did not work. My IDE is idea.

Maven pom is:

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
    </dependency>

I can't find out why it doesn't work. It is just a simple demo. It's too wired.

标签: javajunitmockito

解决方案


It seems due to the fact that you are expecting personDao.update to be invoked 3 times and actually in your method personService.update(1, "new name"); it is getting invoked only 1 time


推荐阅读