使用Mockito java.lang.nullpointerexception进行测试

时间:2016-05-05 14:58:41

标签: java junit mocking mockito

我正在使用junit和mockito(用于业务层)测试我的网络应用程序。

我有一个实体:

@Entity
@Table(name = "brand")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Brand.findAll", query = "SELECT b FROM Brand b"),
    @NamedQuery(name = "Brand.findByOid", query = "SELECT b FROM Brand b WHERE b.oid = :oid"),
    @NamedQuery(name = "Brand.findByName", query = "SELECT b FROM Brand b WHERE b.name = :name")})
public class Brand implements Serializable {
...

和会话bean

@Stateless
public class BrandFacade extends AbstractFacade<Brand> {

    @PersistenceContext(unitName = "MyWheelJSFPU")
    private EntityManager em;

    public void setEm(EntityManager em) {
        this.em = em;
    }

    ...
    @Override
    public List<Brand> findAll(){
        return em.createNamedQuery("Brand.findAll", Brand.class).getResultList();
    }
    ...

现在我想测试.findAll

public class BrandFacadeTest {

    @Mock
    private EntityManager mockedEntityManager;
    @Mock
    private TypedQuery mockedQuery;
    private BrandFacade brandFacade;

    public BrandFacadeTest() {
    }

    @BeforeClass
    public static void setUpClass() {
        System.out.println("Start BrandFacadeTest");
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void initDependencies() {
        brandFacade=new BrandFacade();
        brandFacade.setEm(mockedEntityManager);
        System.out.println("mockEmCreated");
    }

    /**
     * Test of findAll method, of class BrandFacade.
     */
    @Test
    public void testFindAll() {
        System.out.println("findAll");
        List<Brand> brands=new  ArrayList<>();

        when(mockedEntityManager.createNamedQuery("Brand.findAll", Brand.class)).thenReturn(mockedQuery);
        when(mockedQuery.getResultList()).thenReturn(brands);
        int initNumber=brandFacade.findAll().size();

        //creating Brand
        Brand b1 = new Brand(1, "mo");
        brandFacade.create(b1);
        verify(mockedEntityManager, times(1)).persist(any());

        brands.add(b1);
        assertEquals("error",initNumber+1, brandFacade.findAll().size());
    }
    ...

在这一行

when(mockedEntityManager.createNamedQuery("Brand.findAll", Brand.class)).thenReturn(mockedQuery);

它返回一个java.lang.nullpointerexception ...为什么???有什么问题?

我为另一个实体做了完全相同的工作!

1 个答案:

答案 0 :(得分:2)

如果要使用@Mock注释,则必须使用MockitoJUnitRunner运行unittest,或者在测试用例@Before子句中设置以下内容:

MockitoAnnotations.initMocks(BrandFacadeTest);

见这里:http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Mockito.html#mock_annotation