使用@Autowired注释进行Spring JUnit测试

时间:2011-12-13 10:27:00

标签: spring unit-testing junit

我在其中一个被测试的类中引入了@Autowired后,我的测试用例出现了问题。

我的测试用例现在看起来像这样:

@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注释的测试用例进行哪些更改?

编辑:

我现在已将s​​etUp()更新为此(我需要密码编码器以避免空密码):

@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没有被自动装配?

1 个答案:

答案 0 :(得分:3)

如果您不想在StudentRepository引用的某个XML文件中声明@ContextConfiguration并将其自动装入测试,则可以尝试使用AutowireCapableBeanFactory,如下所示:< / p>

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

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