简体   繁体   English

Spring Testing - 使用嵌套的bean依赖项注入mocked bean

[英]Spring Testing - Inject mocked bean with nested bean dependencies

I have a Bean structure like so (but with many more levels): 我有一个像这样的Bean结构(但有更多级别):

@Controller
public class MyController {
    @Autowired
    private MyService myService;
}

@Service
public class MyService {
    @Autowired 
    private MyDao myDao;
}

@Repository
public class MyDao {

}

and I want to unit test MyController with MockMvc . 我想用MockMvcMyController进行单元测试。 If I create a context that creates a MyController instance, it expects a MyService instance for injection, which expects a MyDao instance, and so on. 如果我创建一个创建MyController实例的上下文,它需要一个MyService实例进行注入,它需要一个MyDao实例,依此类推。 Even if I mock MyService like (no component scan) 即使我模拟MyService (没有组件扫描)

@Bean
public MyController myController() {
    MyController controller = new MyController ();
    return controller;
}

@Bean
public MyService myService() {
    return Mockito.mock(MyService.class);
}

Spring will see the @Autowired for MyDao inside MyService and try to find one in the context. Spring将在MyService看到@Autowired for MyDao ,并尝试在上下文中找到一个。 It will obviously fail and throw an exception. 它显然会失败并抛出异常。 I can create a context that has mocks for each and every one one of my classes, but I'd rather not. 我可以为我的每一个类创建一个包含模拟的上下文,但我宁愿不这样做。

Is there any way I can tell Spring not to inject the fields of a bean or a different way of simply injecting the one mock I need in my controller to be tested with MockMvc ? 有什么方法可以告诉Spring不要注入bean的字段或者只是简单地注入我需要在我的控制器中使用MockMvc进行测试的MockMvc吗?

You could use standalone mockMvc if you do want to unit test the controller. 如果您想对控制器进行单元测试,可以使用独立的mockMvc。

 private MockMvc mockMvc;

 private SomeController controller = new SomeController();
 @Mock 
 private ResourceAdminService resourceAdminService;


 @Before
 public void setup() throws Exception {
    controller.setResourceAdminService(resourceAdminService);
    this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
 }

If you still want to setup an ApplicationContext, but it's too annoying with the DI. 如果您仍然想要设置ApplicationContext,但它对DI太烦人了。 Maybe you'll interested in this article( http://java.dzone.com/articles/how-use-mockstub-spring ). 也许你会对这篇文章感兴趣( http://java.dzone.com/articles/how-use-mockstub-spring )。 But the Strategy C:Dynamic Injecting will rebuild an ApplicationContext per test which could slow you tests if you have too many @Test methods. 但是策略C:动态注入将在每个测试中重建一个ApplicationContext,如果你有太多的@Test方法,这可能会减慢你的测试速度。

您可以使用spring-reinject覆盖全局模拟的特定bean,请参阅https://github.com/sgri/spring-reinject/wiki/User%27s-Guide

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

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