如何存根 Spring 存储库以在集成测试中抛出异常?

我有一个服务,它有一个存储库作为构造函数的参数。


@Autowired

NodeServiceListInstallService( final BykiListRepository aBykiListRepository )

该BykiListRepository是没有实现默认春库


interface BykiListRepository extends JpaRepository<BykiList, Long> {

    //some magic methods

}

我的配置类标有@EnableJpaRepositories,所以,我没有直接bean的声明。服务声明:


@SpringBootApplication

@EnableConfigurationProperties( ApplicationProperties )

@EnableJpaRepositories

@EnableTransactionManagement

@ImportResource( 'classpath:META-INF/spring/application-context.xml' )

class Application extends SpringBootServletInitializer {

    @Bean

    NodeServiceListInstallService nodeServiceListInstallService( final BykiListRepository bykiListRepository ) {

        new NodeServiceListInstallService( bykiListRepository )

    }

}

我正在尝试在存储库方法的调用中编写一个测试save将引发异常PersistenceException。我尝试存根/监视一个存储库并将其声明为@TestConfigurationwith 中的 bean @Primary,甚至实现该接口。但我还没有得到结果。


@TestConfiguration

class TestConfig {

    @Bean

    BykiListRepository bykiListRepository() {

        //return Spock's Spy/Stub or new BykiRepositoryBadImpl()

    }

测试:


@ContextConfiguration( classes = TestConfig )

class GlobalErrorHandlerIntegrationTest extends BaseFlowIntegrationTest {

    //test()

}

我Groovy-2.4.12用Spock-1.1. Spring Boot 1.5.4. 保留的变体是使用方面,但不完全是我想要的。将非常感谢帮助。


MM们
浏览 156回答 2
2回答

侃侃尔雅

您可以test configuration像下面那样创建并在调用某个函数时使用 Spock 记录,然后将抛出 ex。当然,@Inject or @Autowire在测试类中使用......并做@Import([IntegrationTestMockingConfig])@TestConfigurationclass IntegrationTestMockingConfig {&nbsp; &nbsp; &nbsp;private DetachedMockFactory factory = new DetachedMockFactory()&nbsp; &nbsp; &nbsp;@Bean&nbsp; &nbsp; &nbsp;ExternalRepository externalRepository() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;factory.Mock(ExternalRepository)&nbsp; &nbsp; &nbsp;}}

智慧大石

问题是因为我的 bean 名称错误。我已将其更改为bykiListRepositoryMock( 而不是bykiListRepository) 并解决了问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java