无法同时向Spock和Spring注入Spring依赖项

时间:2019-02-02 20:56:47

标签: spring spring-boot dependency-injection spock

我在设置测试时遇到麻烦。我正在使用SpringBoot和Spock Framework的最新版本。首先,我不是我的配置豆“传统”的方式。我的所有课程中除了包Facade是包范围的。我不使用@Component@Service,等

Im注入的唯一一个类是Repository。让我告诉你我的Configuration

@Configuration
class SurveyConfiguration {
    @Bean
    SurveyFacade surveyFacade(SurveyRepository surveyRepository) {
        ConversionUtils conversionUtils = new ConversionUtils();
        SurveyValidator surveyValidator = new SurveyValidator();
        SurveyCreator surveyCreator = new SurveyCreator(surveyRepository, conversionUtils, surveyValidator);
        return new SurveyFacade(surveyCreator);
    }
}

它工作正常,我已经手动测试了所有方案(将POST发送到某些端点)。让我告诉你方法,例如从SurveyCreator类我想测试。

SurveyDTO createSurvey(final SurveyDTO surveyDTO) throws ValidationException, PersistenceException {
    Survey survey = conversionUtils.surveyToEntity(surveyDTO);
    surveyValidator.validate(survey);        
    Optional<Survey> savedInstance = Optional.ofNullable(surveyRepository.save(survey)); //Will throw NullPtr
    return savedInstance.map(conversionUtils::surveyToDTO)
            .orElseThrow(PersistenceException::new);
}

就像我说的那样,在运行时它运行良好。因此,让我们继续进行测试

@SpringBootTest
class SurveyFacadeTest extends Specification {
    @Autowired
    private SurveyRepository surveyRepository
    private SurveyFacade surveyFacade = new SurveyConfiguration().surveyFacade(this.surveyRepository)

    def "should inject beans"() {
        expect:
            surveyRepository != null
            surveyFacade != null
    }
    def "should create survey and return id"() {
        given:
           Long id
        when:
            id = surveyFacade.createSurvey(SampleSurveys.validSurvey())
        then:
            id != surveyFacade
    }
}

首先测试通过,让我明白了我一切OK了测试。但是,我在我的方法上面张贴了我的Java代码越来越空指针。看起来SurveyRepository并没有在测试期间注入到Java代码中,因为那是导致此异常的原因...任何解决方法,如何在Spring应用程序和Spock测试中注入我的Repository

1 个答案:

答案 0 :(得分:1)

如果没有理由反对,我建议您在“底层bean”(而不是手动创建的实例)上运行测试:

@Autowired
private SurveyFacade surveyFacade;