mercredi 28 octobre 2015

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

Suppose I have a class called MainClass.

public class MainClass {
    @Autowired
    AutoWiredClass autoWiredClass;
}

I am trying to create a mock bean of MainClass using Mockito.

@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. 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. Please help me how to achieve this.

Aucun commentaire:

Enregistrer un commentaire