問(wèn)題描述
我有一個(gè)我想測(cè)試的類.只要有可能,我就會(huì)對(duì)依賴于其他類對(duì)象的類進(jìn)行依賴注入.但是,我遇到了一個(gè)案例,我想在不重組對(duì)象的情況下模擬對(duì)象代碼而不是應(yīng)用 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.
這是被測(cè)試的類:
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;
}
}
我的測(cè)試類是:
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
}
}
我想不出一個(gè)解決方案來(lái)模擬 Dealer 類中的打印對(duì)象.因?yàn)?,我?Test 類中模擬它,但它是在被測(cè)方法中創(chuàng)建的.我做了我的研究,但不能找到任何好的資源.
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.
我知道從這個(gè)方法中創(chuàng)建打印對(duì)象并注入對(duì)象是更好的方法,但我想測(cè)試代碼原樣,在方法內(nèi)部創(chuàng)建打印對(duì)象.有什么辦法嗎這個(gè)
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 實(shí)例來(lái)調(diào)用怎么樣?
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);
順便說(shuō)一句,我對(duì)您的以下代碼感到困惑:-
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?
這篇關(guān)于在測(cè)試中的方法內(nèi)部創(chuàng)建的模擬對(duì)象的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!