当前位置: 首页 > 知识库问答 >
问题:

在集成测试期间为SpEL Bean引用注册模拟Bean

卫振
2023-03-14

当我从spring-boot应用程序运行测试时,我得到了以下错误。我使用版本=2.3.3.spring-boot-starter-data-mongoDb和版本=2.2.0的de.flapdoodle.embed.mongo进行集成测试。

org.springframework.expression.spel.SpelEvaluationException: EL1058E: A problem occurred when trying to resolve bean 'gameServiceImpl':'Could not resolve bean reference against BeanFactory'

    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:59)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:55)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:91)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:117)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:308)
    at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity.getCollection(BasicMongoPersistentEntity.java:129)
    at org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation.getCollectionName(MappingMongoEntityInformation.java:97)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:88)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy70.save(Unknown Source)
    at eatigo.com.webscraper.service.GameServiceImplTest.testSavingSingleEntity(GameServiceImplTest.java:107)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.expression.AccessException: Could not resolve bean reference against BeanFactory
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:54)
    at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:55)
    ... 89 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'gameServiceImpl' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
    at org.springframework.context.expression.BeanFactoryResolver.resolve(BeanFactoryResolver.java:51)
    ... 90 more
    null
@Document(collection = "#{@gameServiceImpl.getCollectionName()}")
public class Game {
    @Id
    private int gameId;
}
@Repository
public interface GameRepository extends MongoRepository<Game, String> {
}
@Service
public class GameServiceImpl implements GameService {

    private GameRepository gameRepository;
    private String collectionName;

    @Autowired
    public GameServiceImpl(GameRepository gameRepository){
        this.gameRepository = gameRepository;
    }

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }

    public Game save(Game game){
        return gameRepository.save(game);
    }
}
ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@SpringBootTest(classes = {MainApplication.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@DataMongoTest
public class GameServiceImplTest {

    @Mock(name = "gameServiceImpl")
    private GameServiceImpl gameServiceImpl;

    @Autowired
    private GameRepository gameRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSavingGame(){
        Game game= new Game();

        String collectionName = "testing";
        gameServiceImpl.setCollectionName(collectionName);
        when(gameServiceImpl.save(game)).thenReturn(gameRepository.save(game));
        when(gameServiceImpl.getCollectionName()).thenReturn(collectionName);

        Game result = gameServiceImpl.save(game);

        assertThat(result, is(notNullValue()));
        assertThat(mongoTemplate.collectionExists(collectionName), is(true));
        assertThat(mongoTemplate.findAll(Game.class, collectionName).size(), equalTo(1));
    }
}

共有1个答案

晁璞
2023-03-14

感谢@M。Deinum的方向和一些帮助从这里,我能够实现与以下修改的结果。

测试

@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@DataMongoTest
public class GameServiceImplTest {

    @MockBean(name = "gameServiceImpl")
    public GameServiceImpl gameServiceImpl;

    @Autowired
    private GameRepository gameRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void testSavingSingleEntity(){
        Game game = new Game();

        String collectionName = "testingCollection";
        gameServiceImpl.setCollectionName(collectionName);
        when(gameServiceImpl.getCollectionName()).thenReturn(collectionName);

        Game result = gameRepository.save(game);
        when(gameServiceImpl.save(game)).thenReturn(result);

        assertThat(gameServiceImpl.save(game), is(notNullValue()));
        assertThat(mongoTemplate.collectionExists(collectionName), is(true));
        assertThat(mongoTemplate.findAll(Game.class, collectionName).size(), equalTo(1));
    }
}
 类似资料:
  • 我们有一些传统的laravel项目,它们在类中使用正面。 我们最近的项目使用了底层laravel类的依赖注入,facades所代表的类正如Taylor Otwell自己所暗示的那样。(我们对每个类使用构造函数注入,但为了保持示例简短,这里我使用方法注入并使用单个类。) 我知道外表是可以被嘲笑的 这对单元测试很有效。我试图理解的问题是,这些门面是否被“全球”嘲笑。 例如,让我们假设我正在编写一个集成

  • 如何模拟集成测试所需的许多依赖关系? 我使用Mockito进行纯单元测试。在这种情况下,Pure意味着测试一个类,嘲笑它的所有依赖关系。漂亮。 现在是集成测试。假设在这种情况下,集成测试将测试以下内容: 消息被放入队列 我们也可以说,在第2步中发生的处理是严肃的事情。它依赖于大量的数据库交互、多种外部服务、文件系统,以及各种各样的东西。流还会引发很多副作用,所以我不能简单地确保响应是正确的——我需

  • 第一个问题:如何注入模拟(或真实?)HttpServletResponse在我对CXF JAX-RS服务endpoint进行单元测试期间? 我们的服务是如何设置的示例(注意我没有控制/权限来更改非测试结构): 测试类: 我可能在这里做错了几件事,但是我希望我只需要在我的自定义调用器中加入正确的“魔法”,以便正确地向我的endpoint注入HttpServlet响应。我要注意的是,在我没有注入上下文

  • 我正在尝试试驾我正在对我的Android服务进行的一系列更改()-我正在使用Dagger和Robolectric,我需要用一些模拟来替换服务中的字段注入类,以缩小测试范围…使它(稍微)更像“单元”。 我在我的中插入

  • 我发现可以使用以下方法模拟和: 它工作得很好,但当我尝试运行集成测试时,授权服务器仍然需要启动并运行。否则,Quarkus无法连接到它。 我试图禁用OIDC扩展(),但是代码当然不能编译(endpoint不能识别依赖项)。 那么,在运行集成测试时,哪一种方法是跳过OIDC连接的最佳方法呢? 最好的,

  • 问题内容: 每当我想测试使用资源注入的类时,我最终都会包含一个仅在测试中使用的构造函数: 还有另一种模拟资源注入的方式,或者这是遵循的正确模式吗? 问题答案: 您可以使用简单的光泽效果,它可以模拟EJB注入系统。 另一种方法是在测试中使用反射来设置字段,我有时使用类似这样的内容: