带有@Autowired批注的Spring JUnit测试

带有@Autowired批注的Spring JUnit测试,第1张

概述在被测类之一中引入@Autowired之后,我的测试用例出现了问题.我的测试用例现在看起来像这样:@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={'/applicationContext.xml', '/spring-security.xml'}) public

在被测类之一中引入@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;@Beforepublic voID setUp() {    studentRepository = new StudentRepository();    studentRepository.setJdbcTemplate(getJdbcTemplate());    testStudent = Utils.testStudentNoApplication();}@Test....

}

StudentRepository现在看起来像这样:

@Servicepublic 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()更新为此(我需要密码编码器以避免空密码):

@Beforepublic 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);        ...    }    ...}
总结

以上是内存溢出为你收集整理的带有@Autowired批注的Spring JUnit测试 全部内容,希望文章能够帮你解决带有@Autowired批注的Spring JUnit测试 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1237033.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存