【问题标题】:Mocking a Supplier<>-Bean模拟一个 Supplier<>-Bean
【发布时间】:2022-12-08 21:00:55
【问题描述】:

我想模拟一个像这样定义的 Bean(使用 mockito)

@Bean("idGenerator")
public Supplier<UUID> idGenerator() {
  return () -> UUID.randomUUID();
}

SpringBootTest-class 中,我使用 @MockBean 时收到一个错误,表明该 Bean 无法被模拟(由于 JVM 中的一些限制? - 抱歉,我现在手头没有堆栈跟踪)。

我想出了一个解决方法,它不使用 Mocks,而是使用 @TestConfiguration 中的一个附加字段,以便可以在外部指定供应商的返回值。

因为我不太喜欢这种解决方法(我的同事也不会),所以我希望有一个经过验证的模式或者意识到我在做那个嘲笑是错误的。

编辑

这是我得到的堆栈跟踪。正如 Markus 指出的那样——标准的单元测试有效——这似乎是 cucumber-java 的一个缺点:

Before All/After All failed
io.cucumber.core.exception.CompositeCucumberException: There were 15 exceptions. The details are in the stacktrace below.
    at io.cucumber.core.runtime.RethrowingThrowableCollector.getThrowable(RethrowingThrowableCollector.java:57)
    at io.cucumber.core.runtime.CucumberExecutionContext.getThrowable(CucumberExecutionContext.java:102)
    at io.cucumber.core.runtime.CucumberExecutionContext.finishTestRun(CucumberExecutionContext.java:97)
    at io.cucumber.core.runtime.Runtime.execute(Runtime.java:96)
    at io.cucumber.core.runtime.Runtime.run(Runtime.java:87)
    at io.cucumber.core.cli.Main.run(Main.java:87)
    at io.cucumber.core.cli.Main.main(Main.java:30)
    Suppressed: java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
        at io.cucumber.spring.TestContextAdaptor.<init>(TestContextAdaptor.java:32)
        at io.cucumber.spring.SpringFactory.start(SpringFactory.java:120)
        at io.cucumber.core.runner.Runner.buildBackendWorlds(Runner.java:134)
[...]
    Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name [...]: Unsatisfied dependency expressed through constructor parameter 5: Initialization of bean failed; 
    nested exception is org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class BackendApplicationConfiguration$$Lambda$1713/0x00000008018fd980
Mockito cannot mock/spy because :
 - VM does not support modification of given type
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)

【问题讨论】:

    标签: spring-boot testing mockito spring-boot-test cucumber-java


    【解决方案1】:

    你可以像下面这样定义它:

    @MockBean(name = "idGenerator")
    private Supplier<UUID> mockedSupplier;
    

    没有任何问题可以阻止这个嘲笑。最好包含您的堆栈跟踪,因为问题可能出在其他地方。

    【讨论】:

    • 谢谢 - 这是一个重要的信息应该工作。似乎是 cucumber-java 的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 2018-06-01
    • 2020-10-23
    • 2021-09-02
    • 1970-01-01
    • 2011-11-13
    • 2019-06-09
    相关资源
    最近更新 更多