use*_*395 7 java junit mocking junit4 mockito
我有一个我想测试的类。只要有可能,我就会为那个依赖于其他类的对象的类进行依赖注入。但是,我遇到了一种情况,我想在不重构代码的情况下模拟对象而不是应用 DI。
这是被测类:
public class Dealer {
public int show(CarListClass car){
Print print=new Print();
List<String> list=new LinkedList<String>();
list=car.getList();
System.out.println("Size of car list :"+list.size());
int printedLines=car.printDelegate(print);
System.out.println("Num of lines printed"+printedLines);
return num;
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试课程是:
public class Tester {
Dealer dealer;
CarListClass car=mock(CarListClass.class);
List<String> carTest;
Print print=mock(Print.class);
@Before
public void setUp() throws Exception {
dealer=new Dealer();
carTest=new LinkedList<String>();
carTest.add("FORD-Mustang");
when(car.getList()).thenReturn(carTest);
when(car.printDelegate(print)).thenReturn(9);
}
@Test
public void test() {
int no=dealer.show(car);
assertEquals(2,number);//not worried about assert as of now
}
}
Run Code Online (Sandbox Code Playgroud)
我想不出在 Dealer 类中模拟打印对象的解决方案。因为,我在 Test 类中模拟它,但它是在被测方法中创建的。我做了我的研究,但找不到任何好处资源。
我知道从这个方法中创建打印对象并注入对象是更好的方法,但我想按原样测试代码,在方法内部创建打印对象。有没有办法做到这一点
如果你只是想模拟 car.printDelegate() 的返回值,那么模拟调用的任何 Print 实例怎么样?
when(car.printDelegate(org.mockito.Matchers.any(Print.class))).thenReturn(9);
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我对您的以下代码感到困惑:-
List<String> list=new LinkedList<String>(); // allocate a empty list worth
list=car.getList(); // nothing but wasting memory.
...
return num; // no definition, do you mean printedLines?
Run Code Online (Sandbox Code Playgroud)