2

I am pretty new to Mockito and have a question.

I am using Spring's dependency injection for my app and try to test components. I have a test like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(// @formatter:off
    loader = SpringockitoAnnotatedContextLoader.class,
    classes = { TestContext.class }) // @formatter:on
public class TestClass {

@Autowired
private TestBean testBean;

@Test
public void testSomething() {

// do anything
assertTrue(testBean.getClass().getName().equals("TestBean"));
}

}

}

ContextClass:

@Configuration
public class TestContext {

@Bean(name = "testBean")
public TestBean getTestBean() {
    return Mockito.mock(TestBean.class);
}

} 

TestBean.class:

@Component
public class TestBean {

@Autowired
private AnotherTestBean anotherTestBean;

}

AnotherTestBean.class:

@Component
public class AnotherTestBean {

}

Now if I run this code, I get an error caused by:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [info.imapping.application.configuration.context.AnotherTestBean] 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)}

This means Spring tried to inject dependencies into my mocked bean. Can somebody tell me how to prevent this behavior?

If I use @ReplaceWithMock in my TestClass, it works. But I would prefer setting my mock ups in the context file.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
DAndy
  • 117
  • 11

1 Answers1

0

You must declare anotherTestbean as a spring managed bean as you did with testBean. The error happens when spring try to put anotherTestBean in TestBean but there is no such bean in the spring context.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
Morteza Adi
  • 2,413
  • 2
  • 22
  • 37