我正在用junit和mockito(针对业务层)测试我的web应用程序。
我有一个实体:
@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…为什么???怎么了?
我为另一个实体做了完全相同的东西,它起作用了!
如果您想使用@Mock注释,您必须使用MockitoJUnitRunner运行unittest,或者在您的测试用例@Before子句中设置以下内容:
MockitoAnnotations.initMocks(BrandFacadeTest);
请参见此处:http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Mockito.html#mock_annotation