测试开始和测试结束时的java JUnit指令

时间:2015-09-28 16:18:50

标签: sql junit

JUnit(或其他)中是否有可用的注释只能在测试开始时和结束时启动指令?例如:在测试开始时启动SQL会话并在结束时关闭它。 @Before和@After - 不是一个选择((( 从测试中提取:

public class HibernateTest {
    @Autowired
    SessionFactory sessionfactory;

    @Autowired
    DataSource dataSource;

    Session session;
    Transaction tx;

//  @Transactional(propagation=Propagation.REQUIRES_NEW)
    @Before
    public void setUp() throws MalformedURLException, SQLException, DatabaseUnitException {
        session = sessionfactory.openSession();
        tx = session.beginTransaction();
        String sql_categories = "ALTER SEQUENCE categories_category_id_seq1 RESTART WITH 1";
        String sql_projects = "ALTER SEQUENCE projects_project_id_seq1 RESTART WITH 1";
        String sql_donations = "ALTER SEQUENCE donations_donation_id_seq RESTART WITH 1";
        String sql_clear_donations= "delete from donations *";
        String sql_clear_projects = "delete from projects *";
        String sql_clear_categories= "delete from categories *";
        session.createSQLQuery(sql_categories).executeUpdate();
        session.createSQLQuery(sql_projects).executeUpdate();
        session.createSQLQuery(sql_donations).executeUpdate();
        session.createSQLQuery(sql_clear_donations).executeUpdate();
        session.createSQLQuery(sql_clear_projects).executeUpdate();
        session.createSQLQuery(sql_clear_categories).executeUpdate();

    }

    @After
    public void setDown() throws MalformedURLException, SQLException, DatabaseUnitException {
        session.close();
        tx.commit();
    }

//  @Transactional(propagation=Propagation.REQUIRED)
    @Test
    @ExpectedDatabase(
            value = "classpath:ExpectedAddedCategories.xml",
            assertionMode = DatabaseAssertionMode.NON_STRICT//Не проверять все поля. Только те что надо в xml файле, а не все в базе
            )
    public void testAddCategories() {
        Category cat = new Category("sport");
        Category cat2 = new Category("art");
        Category cat3 = new Category("video");

        session.persist(cat);
        session.persist(cat2);
        session.persist(cat3);
    }
}

此代码实际上不起作用。 Eclipse只是冻结,甚至没有结束一个测试(我只展示了一个测试)

1 个答案:

答案 0 :(得分:0)

如果您希望每个课程启动一次,则可以使用@BeforeClass@AfterClass。如果你想要更高级的东西,你可能也想看看@ClassRule