Mocking EntityManager

I get NPE while taunting EntityManager, below is my code,

@Stateless
public class NodeChangeDeltaQueryBean implements NodeChangeDeltaQueryLocal {

    @PersistenceContext
    private EntityManager em;
    @Override
    public String findIdByNaturalKey(final String replicationDomain, final int sourceNodeIndex,
                                     final int nodeChangeNumber) {
        List<String> result =
            NodeChangeDelta.findIdByNaturalKey(this.em, replicationDomain, sourceNodeIndex,
                nodeChangeNumber).getResultList();
        return result.isEmpty() ? null : result.get(0);
    }
}

My entity class

@Entity
public class NodeChangeDelta implements Serializable, Cloneable, GeneratedEntity, KeyedEntity<String> {

public static TypedQuery<String> findIdByNaturalKey(final EntityManager em, final String replicationDomain, final int sourceNodeIndex, final int nodeChangeNumber) {
        return em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class)
            .setParameter("replicationDomain", replicationDomain)
            .setParameter("sourceNodeIndex", sourceNodeIndex)
            .setParameter("nodeChangeNumber", nodeChangeNumber);
    }
}

My test class

@RunWith(MockitoJUnitRunner.class)
public class NodeChangeDeltaQueryBeanTest {

    @InjectMocks
    NodeChangeDeltaQueryBean nodeChangeDeltaQueryBean;

    @Mock
    EntityManager em;

@Test
    public void testFindIdByNaturalKey() {
        this.addNodeChangeDelta();
        this.nodeChangeDeltaQueryBean.findIdByNaturalKey(this.REPLICATION_DOMAIN,
            this.SOURCE_NODE_INDEX, this.NODE_CHANGE_NUMDER);
    }
}

While debugging em is not null (also other arguments REPLICATION_DOMAIN, SOURCE_NODE_INDEX, NODE_CHANGE_NUMDER are not null) in the Entity class, while em.createNamedQuery ("NodeChangeDelta.findIdByNaturalKey", String.class)

+1
source share
2 answers

In the mockito wiki: Don't scoff at types you don't own!

This is not a hard line, but crossing this line can have consequences! (this is likely to be.)

  • , lib. , , . , , , , , ...
  • , .
  • , . , . , , - .

lib/system, , API, , , .

, , () -. EntityManager , , JDK/JSR ( API, JDK). , , , , ( ).

, , , , , .

wiki , , , , .

mock . , Arquillian - , , .


: fooobar.com/questions/1018172/...

+1

Mockito , , null. findIdByNaturalKey em.createNamedQuery null NPE setParameter. RETURN_MOCKS.

, , @InjectMocks @PersistenceContext. , em, , null. , , .

0

All Articles