2011-12-13 55 views
3

在測試中的其中一個類中引入@Autowired後,我的測試用例出現問題。使用@Autowired註解進行Spring JUnit測試

我的測試用例現在看起來是這樣的:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"/applicationContext.xml", "/spring-security.xml"}) 
public class StudentRepositoryTest extends AbstractDatabaseTestCase { 

private StudentRepository studentRepository; 
private CompanyRepository companyRepository; 
private Student testStudent; 
private Company testCompany; 

@Before 
public void setUp() { 
    studentRepository = new StudentRepository(); 
    studentRepository.setJdbcTemplate(getJdbcTemplate()); 
    testStudent = Utils.testStudentNoApplication(); 
} 
@Test 
.... 

}

StudentRepository現在看起來是這樣的:

@Service 
public class StudentRepository extends AbstractRepository<Student> { 

... 

private PasswordEncoder passwordEncoder; 
private MailService mailService; 

public StudentRepository() { 
    // TODO Auto-generated constructor stub 
} 

@Autowired 
public StudentRepository(MailService mailService, PasswordEncoder passwordEncoder) { 
    this.mailService = mailService; 
    this.passwordEncoder = passwordEncoder; 
} 

顯然,這測試用例不需額外的工作了。 但是我需要對測試用例的@Autowired註釋的測試用例進行哪些更改?

編輯:

從來就目前更新我的設置()這個(我需要的密碼編碼器,以避免空口令):

@Before 
public void setUp() { 
    //studentRepository = new StudentRepository(); 
    studentRepository = new StudentRepository(mock(MailService.class), ctx.getAutowireCapableBeanFactory().createBean(ShaPasswordEncoder.class)); 
    studentRepository.setJdbcTemplate(getJdbcTemplate()); 
    testStudent = Utils.testStudentNoApplication(); 
} 

我的測試用例現在運行正常,但我的測試套件用NullPointerException失敗。 我猜測由於某種原因運行測試套件時ApplicationContext未被自動裝配?

+0

這是隻在一個問題考試? Spring會以某種方式出現異常嗎? – hellectronic

+2

如果它是一個單元測試,你可能應該將模擬MailService和PasswordEncoder實例傳遞給你的StudentRepository的構造函數。查看Mockito,EasyMock或任何其他模擬API。 –

回答

3

如果你不希望你的聲明中StudentRepository@ContextConfiguration引用的XML文件之一,它自動裝配到測試,你可以嘗試使用AutowireCapableBeanFactory如下:

... 
public class StudentRepositoryTest extends AbstractDatabaseTestCase { 
    ... 
    @Autowired ApplicationContext ctx; 

    @Before 
    public void setUp() { 
     studentRepository = ctx.getAutowireCapableBeanFactory() 
           .createBean(StudentRepository.class); 
     ... 
    } 
    ... 
} 
+0

謝謝,這個工作,或至少更好的作品。我遇到了一個新的異常(UnsatisfiedDependency),但是正如JB Nizet在上面的評論中提到的那樣,我應該把mock傳遞給構造函數。 – Daniel

+0

@Daniel:是的,我的解決方案假定'MailService'和'PasswordEncoder'在'@ ContextConfiguration'引用的配置中聲明,並且您想對它們進行測試。如果你需要模擬,請使用mock。 – axtavt

+0

一些成功,但還是有些問題。我已更新了我的第一篇文章。 – Daniel