Daniel
Daniel

Reputation: 2500

Spring JUnit testing with @Autowired annotation

I´m having issues with my test cases after having introduced @Autowired in one of the classes under test.

My testcase now looks like this:

@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 now looks like this:

@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;
}

Obviously this test case won´t work anymore. But what changes do I need to make to the testcase for the @Autowired annotation to be picked up by the test case?

EDIT:

I´ve now updated my setUp() to this (I need the password encoder to avoid null password):

@Before
public void setUp() {
    //studentRepository = new StudentRepository();
    studentRepository = new StudentRepository(mock(MailService.class), ctx.getAutowireCapableBeanFactory().createBean(ShaPasswordEncoder.class));
    studentRepository.setJdbcTemplate(getJdbcTemplate());
    testStudent = Utils.testStudentNoApplication();
}

My testcase is now running OK, but my testsuite failes with a NullPointerException. I´m guessing the ApplicationContext is not being Autowired when running the testsuite for some reason?

Upvotes: 4

Views: 19091

Answers (1)

axtavt
axtavt

Reputation: 242686

If you don't want to declare your StudentRepository in one of XML files referenced by @ContextConfiguration and autowire it into the test, you can try to use AutowireCapableBeanFactory as follows:

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

    @Before
    public void setUp() {
        studentRepository = ctx.getAutowireCapableBeanFactory()
                               .createBean(StudentRepository.class);
        ...
    }
    ...
}

Upvotes: 4

Related Questions