日常排BUG1 - Java测试junit之@Test+@Before+@After

场景:hibernate建立(@Before)关闭(@After)session的时候
BUG: java.lang.NullPointException
排BUG心得:@Before+@After,只在@Test对应方法中前后执行,而对在@Test对应方法中的其他方法无效

案例1-执行成功,在select()方法中可以打印出session

    Session session;
    Transaction tx;
    @Before
    public void initData() {
        session = HibernateSessionFactory.getSession();
        tx = session.beginTransaction();
    }
    @After
    public void afterTest() {
        tx.commit();
        HibernateSessionFactory.closeSession();
    }

    // 查询
    @Test
    public void select() {
        System.out.println("session:" + session);
        Dept dept1 = (Dept) session.get(Dept.class, 1);
        System.out.println(dept1);
    }

案例2-执行失败,在select()方法中无法打印出session

    Session session;
    Transaction tx;
    @Before
    public void initData() {
        session = HibernateSessionFactory.getSession();
        tx = session.beginTransaction();
    }

    @After
    public void afterTest() {
        tx.commit();
        HibernateSessionFactory.closeSession();
    }

    // 增加
    public void addDeptBySql(int dept_id, String dept_name) {
        System.out.println("session:" + session);     //打印出session:null
        String sql = "insert into dept(dept_id,dept_name)  values(:dept_id,:dept_name)";    //出现java.lang.NullPointException的语句
        Query q = session.createSQLQuery(sql);
        System.out.println(q.getQueryString());
        q.setInteger("dept_id", dept_id);
        q.setString("dept_name", dept_name);
        q.executeUpdate();
        session.close();
    }

    @Test
    public void addDeptBySqlTest(){
        new HibernateSQLOrHQL().addDeptBySql(4, "人事部");
        System.out.println("成功添加");
    }

案例2解决方案:将@Before方法去掉,将里面的内容放到代码块中

    Session session;
    Transaction tx;
     {        //修改部分
        session = HibernateSessionFactory.getSession();
        tx = session.beginTransaction();
    }

    @After
    public void afterTest() {
        tx.commit();
        HibernateSessionFactory.closeSession();
    }

    // 增加
    public void addDeptBySql(int dept_id, String dept_name) {
        System.out.println("session:" + session);     //打印出session
        String sql = "insert into dept(dept_id,dept_name)  values(:dept_id,:dept_name)";   
        Query q = session.createSQLQuery(sql);
        System.out.println(q.getQueryString());
        q.setInteger("dept_id", dept_id);
        q.setString("dept_name", dept_name);
        q.executeUpdate();
        session.close();
    }

    @Test
    public void addDeptBySqlTest(){
        new HibernateSQLOrHQL().addDeptBySql(4, "人事部");
        System.out.println("成功添加");
    }

你可能感兴趣的:(日常排BUG1 - Java测试junit之@Test+@Before+@After)