我想模擬調用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