How to mock local variables using mockito or powermock(如何使用 mockito 或 powermock 模拟局部变量)
问题描述
我有这样的场景
我一直嘲讽到现在
现在我得到了一位读者
但是当我执行这一行时,我得到 null 并且无法继续前进
but when I execute this line I get null and not able to move forward
请告诉我如何模拟这个.请注意,我无法更改我的主要代码,因此 Mockito 文档中的解决方案在我的情况下无效
Please tell me how can I mock this. Please note I cannot change my main code therefore the solution present on Mockito docs is not valid in my case
测试代码
推荐答案
要做到这一点,需要使用 Powermockito 来拦截构造函数调用(new InputStreamReader(...), new BufferedReader(...))所以你的模拟得到回报.下面是一个例子.在您的情况下,只需拦截新的 BufferedReader 调用就足够了.
To make this work, you need to use Powermockito to intercept the constructor calls (new InputStreamReader(...), new BufferedReader(...)) so that your mocks get returned. An example is below. In your case, just intercepting the new BufferedReader call may be enough.
假设以下是您要测试的代码:
Assume the following is the code you want to test:
以下测试代码是如何拦截构造函数调用的示例:
The following test code is an example of how to intercept the constructor calls:
希望这能帮助您解决眼前的问题.但是,在我看来,您正在创建的将是一个非常缓慢、令人困惑和脆弱的测试.现在,您的嘲笑太多了,以至于很难确定您实际上要测试什么.
This hopefully helps you in your immediate problem. However, it seems to me that what you're creating will be a very slow, confusing and brittle test. Right now, you're mocking so much that it makes very hard to determine what you're actually trying to test.
大量的模拟可能表明您正在测试的代码的设计需要一些工作来提高可测试性.如果你不能接触代码,那么你就不能——但试着让你的测试更具可读性和直观性(当这个方法被调用时,这件事应该发生,因为......").
The high amount of mocking probably indicates that the design of the code you're testing would need some work to improve testability. If you can't touch the code, then you can't - but try to make your test more readable and intuitive ("When this method is invoked, this thing should happen, because...").
这篇关于如何使用 mockito 或 powermock 模拟局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!