我开始学习Mockito了。我不知道如何模拟我的Parser并使用现有文件,例如带有双数字的“data.txt”,但保存为字符串(21.144 -12.98等)。而且我想查看这些数字不是字母或其他东西。我的解析器:
package model.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
import model.data.HullPoint;
import model.data.HullPointContainer;
public class Parser {
public static HullPointContainer parseFile(File file) throws FileNotFoundException
{
double a, b;
String da, db;
double minx = 0, miny = 0, maxx = 0, maxy = 0;
int k = 0;
LinkedList<HullPoint> list = new LinkedList<HullPoint>();
try{
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()){
da = (lineScanner.next());
db = (lineScanner.next());
a = Double.parseDouble(da);
b = Double.parseDouble(db);
HullPoint point = new HullPoint(a,b);
list.add(point);
if(k == 0){
minx = maxx = a;
miny = maxy = b;
} else {
if(a < minx)
minx = a;
if(a > maxx)
maxx = a;
if(b < miny)
miny = b;
if(b > maxy)
maxy = b;
}
k++;
}
lineScanner.close();
}
int i = list.size();
System.out.println(i);
System.out.println("minX = " + minx +" and minY= " + miny);
System.out.println("maxX = " + maxx +" and maxY= " + maxy);
return new HullPointContainer(list, minx, miny, maxx, maxy);
} catch (Exception e) {
throw e;
} finally {
scanner.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw(e);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
答案 0 :(得分:0)
为了模拟你的解析器,你必须创建一个模拟对象
Parser mockedparser = Mockito.mock(Parser.class);
然后你可以告诉mockito如果调用parseFile
方法该怎么做。例如:
Mockito,when(mockedparser.parseFile(myFile)).thenReturn(result);
当以parseFile
作为参数调用myFile
方法时,模拟将返回result
你可以verify
该方法称之为:
Mockito.verify(mockedparser).parseFile(myFile);
如果已使用此参数调用once
,则检查将通过,如果不是,则检查将失败并显示描述性错误消息
PS:Mocking是simulating
对象行为,没有对象的真实实例。
恕我直言,你应该问你如何Unit test
你的解析器而不是mocking