在被测试的类之一中引入 @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 注释?
编辑:
我现在已将我的 setUp() 更新为此(我需要密码编码器以避免空密码):
@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 没有被自动连接?
最佳答案
如果您不想在 @ContextConfiguration
引用的 XML 文件之一中声明您的 StudentRepository
并将其 Autowiring 到测试中,您可以尝试使用 AutowireCapableBeanFactory
如下:
...
public class StudentRepositoryTest extends AbstractDatabaseTestCase {
...
@Autowired ApplicationContext ctx;
@Before
public void setUp() {
studentRepository = ctx.getAutowireCapableBeanFactory()
.createBean(StudentRepository.class);
...
}
...
}
关于使用 @Autowired 注释进行 Spring JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8487589/