2013-08-17 245 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); 
    } 
} 

你不必寫在每個測試類