gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:54:54 24 4
gpt4 key购买 nike

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

@Autowired
NodeServiceListInstallService( final BykiListRepository aBykiListRepository )

BykiListRepository 是没有实现的默认 Spring 存储库

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。我尝试 stub /监视一个存储库,并在 @TestConfiguration 中使用 @Primary 将其声明为 bean,甚至实现接口(interface)。但是我还没有得到结果。

@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。保留变体是使用方面,但并不完全是我想要的。非常感谢您的帮助。

更新:DetachedMockFactory 的用法:

配置:

@测试配置

class DummyConfiguration {
private final detachedFactory = new DetachedMockFactory()
@Bean
@Primary
BykiListRepository bykiListRepository() {
detachedFactory.Mock( BykiListRepository )
}
}

测试框架:

@SpringBootTest( classes = DummyConfiguration )
@Import( [DummyConfiguration] )
@ContextConfiguration( classes = DummyConfiguration )
class GlobalErrorHandlerIntegrationTest extends BaseFlowIntegrationTest {
@Autowired
BykiListRepository bykiListRepositoryMock
def 'exercise error handling'() {
given: 'the failing repository'
bykiListRepositoryMock.save( _ ) >> {
throw new CannotCreateTransactionException()
}
when: 'the message is send to rabbit'
rabbitOperations.send( configuration.rabbitExchangeName, '', msg )
}
}

哪里:

@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.NONE )
@ContextConfiguration( classes = Application )
class BaseFlowIntegrationTest extends AbstractIntegrationTest {...}

@Category( InboundIntegrationTest )
abstract class AbstractIntegrationTest extends Specification {...}

最佳答案

您可以像下面这样创建测试配置,并在调用某些函数时使用 Spock 记录,然后将抛出 ex。当然,在测试类中使用@Inject 或@Autowire...并执行@Import([IntegrationTestMockingConfig])

@TestConfiguration
class IntegrationTestMockingConfig {

private DetachedMockFactory factory = new DetachedMockFactory()

@Bean
ExternalRepository externalRepository() {
factory.Mock(ExternalRepository)
}
}

关于java - 如何 stub Spring 存储库以在集成测试中抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52204352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com