我想模拟一个Bean(使用mockito),它是这样定义的
@Bean("idGenerator")
public Supplier<UUID> idGenerator() {
return () -> UUID.randomUUID();
}
在一个SpringBootTest
-类中,我使用@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)
1条答案
按热度按时间cngwdvgl1#
您可以像下面这样定义它:
没有任何问题可以阻止它被嘲笑。最好包括你的堆栈跟踪,因为问题可能在其他地方。