問題描述
我有一個我想測試的類.只要有可能,我就會對依賴于其他類對象的類進行依賴注入.但是,我遇到了一個案例,我想在不重組對象的情況下模擬對象代碼而不是應用 DI.
I have a class which I would like to test.Whenever possible I would do dependency injections for that class which depends on object of other classes.But,I ran into a case where I would like to mock the object without restructuring the code and not appling 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;
}
}
我的測試類是:
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
}
}
我想不出一個解決方案來模擬 Dealer 類中的打印對象.因為,我在 Test 類中模擬它,但它是在被測方法中創建的.我做了我的研究,但不能找到任何好的資源.
I couldn't figure out a solution to mock the print object inside the Dealer class.Since,I mock it in the Test class,but it gets created in the method under test.I did my research,but couldn't find any good resource.
我知道從這個方法中創建打印對象并注入對象是更好的方法,但我想測試代碼原樣,在方法內部創建打印對象.有什么辦法嗎這個
I know taking Print object creation out of this method and Injection the object is the better way,but I would like to test the code as it is ,with the print object being created inside the method.Is there any way to do this
推薦答案
如果你只是想mock car.printDelegate() 的返回值,那么mock 任何Print 實例來調用怎么樣?
If you just want to mock the return value of car.printDelegate(), how about mock any Print instance for the call?
when(car.printDelegate(org.mockito.Matchers.any(Print.class))).thenReturn(9);
順便說一句,我對您的以下代碼感到困惑:-
By the way, I'm confusing about your following code:-
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?
這篇關于在測試中的方法內部創建的模擬對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!