2017-05-20 70 views
0

我正在为我的项目编写单元测试,但在调用与数据库一起工作的方法时遇到一些困难。目前,我要检查获取的用户兴趣出版物清单的方法,但我正在逐渐NullPointerException测试持久化方法 - JUnit

public class TestPubManager { 
    private PubManager pFunc; 

    @Before 
    public void initialize() { 
     EntityManager manager = PersistenceManager.INSTANCE.getEntityManager(); 
     em.getTransaction().begin(); 
     PubManager pManager = new PubManager(manager); 
     } 

    @Test 
    public void testGetInterestPubs() { 
     int res = pManager.getInterestPubs(2).size(); 
     assertEquals(20, res); 
    } 
} 

NullPointerException异常是与int res = pManager.getInterestPubs(2).size();行了。我在做什么错误的方式?

回答

0

我找到了解决方案。所以这个问题出现在构造函数中 - 它并没有在@Before注解中初始化,但是当我将它放入测试中时,一切都很顺利。

public class TestPubManager { 
    private PubManager pFunc; 
    EntityManager manager = PersistenceManager.INSTANCE.getEntityManager(); 

    @Before 
    public void initialize() { 
     em.getTransaction().begin(); 
     } 

    @Test 
    public void testGetInterestPubs() { 
     PubManager pManager = new PubManager(manager); 
     int res = pManager.getInterestPubs(2).size(); 
     assertEquals(20, res); 
    } 
}