我想模拟调用getJSONFile(),从json文件返回someJson对象。Mocked方法,但它调用实际的
public class NameClass{
public String getValues() throws Exception
{
HelpingClass e=new HelpingClass();
String name=" ";
String age=" ";
String gender=" ";
JSONObject json= e.getJSONFile();
json.getString("name");
json.getString("age");
json.getString("gender");
System.out.println("Request received is "+json);
------ I have some other logic with JSON received and return string...
}
}
这是我getJSONFile()
public class HelpingClass{
public JSONObject getJSONFile() throws Exception
{
System.out.println("Getting JSON file");
File f = new File("src/main/resources/input.json");
JSONObject json ;
InputStream is = new FileInputStream(f);
String jsonTxt = IOUtils.toString(is);
json=new JSONObject(jsonTxt);
return json;
}
}
这是我的测试案例
@RunWith(MockitoJUnitRunner.class)
public class TestValues {
@InjectMocks NameClass names;
@Mock HelpingClass help;
@Test
public void testgetValues() throws Exception
{
//I am expecting this output
JSONObject addValues=new JSONObject();
addValues.put("name", "Rahul");
addValues.put("age", "30");
addValues.put("gender","male");
//this is what i am returning when help.getJSONFile is called
JSONObject json=new JSONObject();
json.put("name", "Rahul");
json.put("age", "30");
json.put("gender", "male");
//Mocking this call and returning my json
Mockito.when(help.getJSONFile()).thenReturn(json);
String s=names.getValues();
Assert.assertEquals(addValues.toString(),s);
}
}
现在,而不是返回所创建的JSON它返回我,我的JSON喜欢的名字在文件中Rohit年龄是28岁,性别是男性。
为什么这个嘲笑不起作用?从技术上讲,它应该调用模拟方法并返回JSONObject类的json对象(即Rahul,30岁和男性)中的值。
我哪里错了?
您好像还在该方法中使用HElpingClass ..你使用Ex e = new Ex(); ..来得到json –
names.getValues()返回的内容? – mhasan
不,我很抱歉,那是错字。它实际上是在帮助上课。我已编辑代码请现在检查 – Rindha