[英]How to mock local variable obtained from another method of tested class?
I have following class我有以下课程
class MyClass{
public void m(InputStream is){
...
Parser eParser = getExcelFileParser();
eParser.parse(is);
...
eParser.foo();
eParser.bar();
}
public ExcelFileParser getExcelFileParser(){
...
}
}
How to write unit test for method m
at this situation?在这种情况下如何为方法
m
编写单元测试? I want to mock eParser
object only.我只想模拟
eParser
对象。
Is it possible?是否可以?
I use Mockito and PowerMockito我使用 Mockito 和 PowerMockito
You can do what you want in Mockito (no PowerMock needed) using a spy
without changing your code at all.您可以使用
spy
在 Mockito 中执行您想要的操作(不需要 PowerMock),而根本无需更改您的代码。
In your unit test you need to do something like the following:在您的单元测试中,您需要执行以下操作:
ExcelFileParser parser = mock(ExcelFileParser.class);
MyClass myClass = spy(new MyClass());
doReturn(parser).when(myClass).getExcelFileParser();
您可以将 AnotherObject 作为参数传递给方法 m 而不是在方法本身中调用 getAnotherObject() 吗?
Preface: I use EasyMock not Mockito so this may be a bit off.前言:我使用的是 EasyMock 而不是 Mockito,所以这可能有点偏离。
Can't you create an inner subclass of MyClass in your test that overrides getExcelFileParser and has it return a mock?你不能在你的测试中创建一个 MyClass 的内部子类来覆盖 getExcelFileParser 并让它返回一个模拟吗? Like this:
像这样:
public class MyClassMock extends MyClass {
ExcelFileParser _mock;
public MyClassMock(ExcelFileParser mock) {
_mock = mock;
}
@Override
public ExcelFileParser getExcelFileParser() {
return _mock;
}
}
I haven't tested this so there could be issues with this, but the basic idea should be right.我还没有测试过这个所以可能会有问题,但基本的想法应该是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.