如何在 JUNIT 中模拟 EntityManagerFactory

How to Mock EntityManagerFactory In JUNIT

JUNIT 测试如何模拟实体管理器工厂。我正在为 Entity Manager Factory 编写 junit 测试用例,但在 (when().then()) 获取 null 时就在这里。

在你的顶部添加 @ExtendWith(MockitoExtension.class) 测试 class。

参考这个https://www.javadoc.io/static/org.mockito/mockito-junit-jupiter/4.4.0/org/mockito/junit/jupiter/MockitoExtension.html

这段代码对我有用。您应该删除@ExtendWith (SpringExtension.class)。还要删除 Mockito.mock 因为我们在这些字段之上添加了 @Mock。

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.when;
    
@ExtendWith(MockitoExtension.class)
class TestClass {

    @Mock
    private EntityManager entityManager;
    @Mock
    private EntityManagerFactory entityManagerFactory;
    @Mock
    private CriteriaBuilder criteriaBuilder;
    @Mock
    private CriteriaQuery<User> criteriaQuery;

    @Test
    void getSearchData() {
        when(entityManagerFactory.createEntityManager()).thenReturn(entityManager);
        when(entityManager.getCriteriaBuilder()).thenReturn(criteriaBuilder);
        when(criteriaBuilder.createQuery(User.class)).thenReturn(criteriaQuery);
        when(criteriaQuery.from(User.class)).thenReturn(new Root<>());//you can also mock Root object
    }
}