3

我喜欢测试我的弹簧代码:

@ContextConfiguration(locations = { "/applicationContext.xml" })
@Transactional()
public class Test {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

用 eclipse 运行这个测试(作为一个 JUNIT 测试)只会给出一个 Nullpointer-Exception。

我做错了什么?谢谢!

4

2 回答 2

4

只需添加@RunWith(SpringJUnit4ClassRunner.class)到您的课程中:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext.xml" })
@Transactional()
public class Test {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

你需要spring-test那个。

于 2013-08-17T17:41:30.360 回答
2

您可以像这样添加事务测试基类

@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class IntegrateTestBase extends AbstractTransactionalJUnit4SpringContextTests {
}

然后写你的测试类

public class Test extends IntegrateTestBase {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

您无需在每个测试类中编写@ContextConfigurationand@Transcational

于 2013-08-17T17:52:50.153 回答