gpt4 book ai didi

spring - Mockito @InjectMocks 如何工作?

转载 作者:IT老高 更新时间:2023-10-28 13:51:27 30 4
gpt4 key购买 nike

这是我的问题:

我有几个 Web 服务类来测试它们是否都从通用服务继承了它们的方法。我认为我可以按功能区域(即三组测试方法,每组依赖于不同的底层 DAO 方法调用)分解测试套件,而不是为每个测试套件编写单元测试。

我建议做的是:

@Mock StateDAO mockedStateDao;
@Mock CountyDAO mockedCountyDao;
@Mock VisitorDAO mockedVisitorDao;

然后调用:

@InjectMocks CountyServiceImpl<County> countyService = new CountyServiceImpl<County>();
@InjectMocks StateServiceImpl<State> stateService = new StateServiceImpl<State>();
@InjectMocks VisitorServiceImpl<Visitor> visitorService = new VisitorServiceImpl<Visitor>();

如何确保每个 mockedDAO 都被注入(inject)到正确的服务中? Autowiring 所有三个(而不是使用@InjectMocks)会更容易吗?

我正在使用 Spring、Hibernate 和 Mockito...

最佳答案

好吧,尼古拉斯的答案几乎是正确的,但不要猜测,只需查看 InjectMocks 的 javadoc , 它包含更多细节;)

对我来说,在一个测试中包含这么多服务很奇怪,作为一个单元测试或作为一个集成测试感觉都不对。在单元测试中这是错误的,因为你有太多的合作者,它看起来不像面向对象(或 SOLID)。在集成测试中,这很奇怪,因为您测试与数据库集成的代码没有模拟它。

对于 1.9.5 中的快速引用,您有:

Mark a field on which injection should be performed.

Allows shorthand mock and spy injection. Minimizes repetitive mock and spy injection. Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection in order and as described below. If any of the following strategy fail, then Mockito won't report failure; i.e. you will have to provide dependencies yourself.

  1. Constructor injection; the biggest constructor is chosen, then arguments are resolved with mocks declared in the test only.

    Note: If arguments can not be found, then null is passed. If non-mockable types are wanted, then constructor injection won't happen. In these cases, you will have to satisfy dependencies yourself.

  2. Property setter injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the property name and the mock name.

    Note 1: If you have properties with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching properties, otherwise Mockito might get confused and injection won't happen.

    Note 2: If @InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor.

  3. Field injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the field name and the mock name.

    Note 1: If you have fields with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen.

    Note 2: If @InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor.

关于spring - Mockito @InjectMocks 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228777/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com