当前位置: 动力学知识库 > 问答 > 编程问答 >

spring - Use @Primary to precede an @Component/@Service annotated class

问题描述:

In my project I have a service with the @Service annotation.

@Service

public class ExampleService { ... }

I would like to override this service with a Mockito-mock, using a configuration file for my test in the following way:

public class TestContext{

@Bean

@Primary

public ExampleService exampleService(){

return mock(ExampleService.class);

}

}

and in my test class:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = { WebContext.class, TestContext.class})

@WebAppConfiguration

public class TestExample{...}

For some reason the mocks aren't injected. The only way I can make this work is when I don't use @Service (@Component gives the same problem) but use a bean annotated method in the WebContext to load the ExampleService, and I put the TestClass behind the WebContext.class in the ContextConfiguration annotation (like in the code I wrote here). I don't get why, and I would like to know how I can keep using the @Service annotation.

分享给朋友:
您可能感兴趣的文章:
随机阅读: