Search code examples
javajunitmockitoentitymanager

Test EntityManager with JUnit and Mockito


I have tried to test the following class, but I have been unsuccessful.

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public int sendToTableOne()
    {
        return em.createNativeQuery("INSERT INTO TABLE_ONE"
                        + " SELECT * FROM TABLE_TWO")
                .executeUpdate();
    }

How can I test this class?

I'm using JUnit Jupiter on Spring framework.


Solution

  • I don't know if it's a good solution, but I obtain 100% coverage.

    @Mock
    EntityManager entityManager;
    
    @Mock
    Query query;
    
    @InjectMocks
    ThSwapDaoImpl daoImpl;
    
    @BeforeEach
    void setUp() throws Exception {
    }
    
    @Test
    void test() {
        
        when(entityManager.createNativeQuery(anyString())).thenReturn(query);
        when(query.executeUpdate()).thenReturn(1);
        assertEquals(daoImpl.sendToHistorical(), 1);
    
    }