带有@Autowired批注的Spring JUnit测试

前端之家收集整理的这篇文章主要介绍了带有@Autowired批注的Spring 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批注能够被测试用例接受?

编辑:

我现在将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并将其自动连接到测试中,则可以尝试使用AutowireCapablebeanfactory,如下所示:

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

    @Before
    public void setUp() {
        studentRepository = ctx.getAutowireCapablebeanfactory()
                               .createBean(StudentRepository.class);
        ...
    }
    ...
}
原文链接:https://www.f2er.com/spring/531764.html

猜你在找的Spring相关文章