首页 > 解决方案 > 使用 Mockito 测试数据库删除方法

问题描述

我想在 PersonDao 类中测试我的删除方法。

public class PersonDao {
    private EntityManager em;
    Person person1 = new Person(111, "Klara", "Bamp", "qwerty123");

    public PersonDao() {
    }

    public PersonDao(EntityManager em) {
        this.em = em;
    }
    public void delete(Person p) {
        em.remove(p);
    }
}

那是我的测试课:

public class UnitTests {
@Mock
EntityManager entityManagerMock;

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

@Test
public void deletePersonTestWithMockito() {
    //ARRANGE
    PersonDao personDao = new PersonDao(entityManagerMock);
    when(entityManagerMock.find(Person.class, person1.getId())).thenReturn(person1);
    //ACT
    personDao.delete(person1);
    //ASSERT
    verify(entityManagerMock, times(1)).remove(person1);
    assertNull(entityManagerMock.find(Person.class, person1.getId()));
}

我意识到,那 personDao.delete(person1) 什么都不做,因为我没有指定 entityManagerMock.remove 应该做什么。我试图将其指定为 when(entityManagerMock.remove(person1)).thenCallRealMethod();,但收到错误Required type: T; Provided: void

标签: jpamockitodao

解决方案


推荐阅读