加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

带有@Autowired批注的Spring JUnit测试

发布时间:2020-12-15 01:20:27 所属栏目:大数据 来源:网络整理
导读:在被测类之一中引入@Autowired之后,我的测试用例出现了问题. 我的测试用例现在看起来像这样: @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"/applicationContext.xml","/spring-security.xml"})public class StudentRepositor

在被测类之一中引入@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);
        ...
    }
    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读