2013-08-17 247 views
3

我想考验我的春天代码:春JUnit测试

@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测试)只是给出了一个空指针的异常。

我做错了什么?谢谢!

回答

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了点。

+0

谢谢@ContextConfiguration@Transcational!而已! –

+0

@UdoR。我很乐意提供帮助 – t777

2

您可以添加一个事务性测试基类这样

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

然后wirite您的测试类

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); 
    } 
} 

你不必写在每个测试类