Почему @TestConfiguration не создал bean-компонент для моего теста? - PullRequest
0 голосов
/ 28 мая 2020

Моя служба

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

Мой тест

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

}

Ошибка: java .lang.NullPointerException. Я проверил, и stripeService на самом деле имеет значение null.

1 Ответ

1 голос
/ 28 мая 2020

Поскольку вы выполняете автоматическое подключение, вам нужен контекст приложения, чтобы Spring мог управлять компонентом и затем мог быть внедрен в ваш класс. Поэтому вам не хватает аннотации для создания контекста приложения для вашего тестового класса.

Я обновил ваш код, и теперь он работает (с junit 5 в вашем пути к классам). В случае, если вы используете junit 4, это должно быть @RunWith(SpringRunner.class) вместо @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);
    }
}
...