简体   繁体   English

如何为具有自动装配依赖项的类创建模拟 spring bean

[英]How to create a mock spring bean for a class having autowired dependencies

Suppose I have a class called MainClass.假设我有一个名为 MainClass 的类。

public class MainClass {
    @Autowired
    AutoWiredClass autoWiredClass;
}

I am trying to create a mock bean of MainClass using Mockito.我正在尝试使用 Mockito 创建 MainClass 的模拟 bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class AutowiringTest {
    @Configuration
    static class AutowiringTestConfiguration{

        @Bean
        public MainClass mainClass() {
            return Mockito.mock(MainClass.class);
        }
    }

    @Autowired
    MainClass mainClass;

    @Test
    public void testBeanCreation(){
        assertNotNull(mainClass);
    }
}

I am getting this error while running the test case.运行测试用例时出现此错误。

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: autowiring.AutoWiredClass autowiring.MainClass.autoWiredClass; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [autowiring.AutoWiredClass] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I know I can achieve this using @Mock and @InjectMocks.我知道我可以使用 @Mock 和 @InjectMocks 来实现这一点。 But that's not the solution I want.但这不是我想要的解决方案。

My requirement is to create a mock bean of MainClass without creating an actual bean of AutowiredClass.我的要求是创建 MainClass 的模拟 bean,而不创建 AutowiredClass 的实际 bean。 Please help me how to achieve this.请帮助我如何实现这一目标。

As Florian has already commented, you should try to create tests that do not need Spring at all, and you will not have those problems.正如 Florian 已经评论过的,您应该尝试创建根本不需要 Spring 的测试,并且您不会遇到这些问题。

But, if there is no workaround possible, you can use a bit of magic with the AutoMockRegistryPostProcessor .但是,如果没有可能的解决方法,您可以对AutoMockRegistryPostProcessor使用一些魔法。

You just need to add the AutoMockRegistryPostProcessor to the @ContextConfiguration , and it will create mocks for your missing dependencies:您只需要将AutoMockRegistryPostProcessor添加到@ContextConfiguration ,它就会为您缺少的依赖项创建@ContextConfiguration

@ContextConfiguration(classes = { AutowiringTest.class, AutoMockRegistryPostProcessor.class })
public class AutowiringTest {
    // no complains anymore, a mockito mock will be created for AutoWiredClass

The AutoMockRegistryPostProcessor class is not in maven, you will need to copy it in your project. AutoMockRegistryPostProcessor类不在 maven 中,您需要将其复制到您的项目中。

The docu is here .文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM