Why did @TestConfiguration not create a bean for my test?

Viewed 2351

My service

@Service
public class StripeServiceImpl implements StripeService {
    @Override
    public int getCustomerId() {
        return 2;
    }
}

My test

public class StripeServiceTests {
    @Autowired
    StripeService stripeService;

    @TestConfiguration
    static class TestConfig {

        @Bean
        public StripeService employeeService() {
            return new StripeServiceImpl();
        }
    }

    @Test
    public void findCustomerByEmail_customerExists_returnCustomer() {
        assertThat(stripeService.getCustomerId()).isEqualTo(2);
    }   

}

The error: java.lang.NullPointerException. I had checked and the stripeService is actually null.

1 Answers

Since you are autowiring you need an applicationcontext so that Spring can manage the bean and then can get injected in your class. Therefore you are missing an annotation to create the applicationcontext for your testclass.

I have updated your code and it works now(with junit 5 on your classpath). In the case dat you are using junit 4 it should be @RunWith(SpringRunner.class) instead of @ExtendWith(SpringExtension.class):

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfiguration.class)
public class StripeServiceTests {
    @Autowired
    StripeService stripeService;

    @TestConfiguration
    static class TestConfig {

        @Bean
        public StripeService employeeService() {
            return new StripeServiceImpl();
        }
    }

    @Test
    public void findCustomerByEmail_customerExists_returnCustomer() {
        assertThat(stripeService.getCustomerId()).isEqualTo(2);
    }
}
Related