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

标签 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 注释?

编辑:

我现在已将我的 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/

相关文章:

java - 使用文件输入的 Junit 参数化测试

java - maven 无法从测试用例中找到任何包

java - 如何正确部署 webapp 到 openshift?

angularjs - 尝试在 Jasmine 单元测试中使用 $provide 时出错

json - jackson 序列化配置

java - 如何编写数据访问的单元测试?

java - 编写需要 2 个列表的单元测试

unit-testing - 将测试类链接到其主类

java - 如何从外部 IDP 读取/导入角色到 Keycloak

java - Google App Engine 上的 Spring Boot 应用程序 : unable to find main class