• @InjectMocks注入依赖遇到的坑


    我在本地使用@InjectMocks注入依赖时发现@InjectMocks并不能将“被注入类”中所有“被Mook的类”都用“Mook的类”的替换掉,注入的方式似乎没有规则,目前测试结果如下:

    @InjectMocks只会注入给一个成员变量,只注入一次。
    优先级从大到小:没有创建对象的成员变量(无论申明在哪里,但只能有一个,超过一个会空指针) > 创建对象的成员变量(在申明时就创建对象)

    https://akcasoy.wordpress.com/2015/02/13/when-to-use-mockito-spy/

    https://stackoverflow.com/questions/56940679/mockito-cant-inject-mocks

    Here is a no answer. I could not give more because I am really sorry to see so many people use this awkward API relying on reflection while you could do things really clear for the readers of the class by explicitly setting the dependency.

    The thing is, my test throws no exceptions, but it doesn't inject my mock object

    Not surprising. This way of injecting the mock stays quiet even if no injection succeeds. From the InjectMocks javadoc (emphasis is not mine!) :

    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.

    While Mockito does not report failure, I really discourage to use this API.

    About your actual issue, look at that :

    @Autowired
    @InjectMocks
    private IREjercicioDAO rEjercicioDAO;

    You annotate the field with both Spring and Mockito annotation. Do you feel confortable with the order of their processing ? These come from two distinct libraries. I don't tell that it will never work (luck and random exists) but do you really think that it is robust ?

    To achieve your requirement you could write something like that that does things in two explicit steps :
    - objects instantiation : mocking the dependency and inject the spring dependency
    - relationship set : between the mock dependency and the spring dependency

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = ATest.CONTEXT_CONFIGURATION)
    public class REjercicioDAOTest extends ATest {
    
        @Mock 
        private ICustomFileHandler customFileHandler;
    
        @Autowired        
        private IREjercicioDAO rEjercicioDAO;
    
        @Before
        public void before () {    
            MockitoAnnotations.initMocks(this);
            // Set explicitly the fileHandler dependency
            rEjercicioDAO.setFileHandler(customFileHandler);         
        }
     }
  • 相关阅读:
    备忘: Visual Studio 2013 VC++ IDE 使用小贴示。
    获取动态数组指针 所指向数组长度的一种方法
    备忘:C++ 类 (初学之实录)。
    备忘:VC++ 中的异常处理
    备忘: C++中的 vector 容器
    备忘:C++基础 -- 数据类型的学习总结
    Windws Server 2008 R2 WEB环境配置之MYSQL 5.6.22安装配置
    Windows Server 2008 R2 WEB服务器配置系列文章索引
    php学习过程二
    php学习过程一
  • 原文地址:https://www.cnblogs.com/pomodoro/p/12929516.html
Copyright © 2020-2023  润新知