我正在尝试模拟对 getJSONFile() 的调用,该调用从 json 文件返回 someJson 对象。
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 岁,男性。
我哪里错了?
最佳答案
如果您在方法内部实例化 HelperClass,@InjectMocks 将无法工作。
你必须使它成为一个实例变量或使用一个你将模拟的 getter:
public class NameClass{
public String getValues() throws Exception
{
HelpingClass e= getHelpingClass();
....
}
HelpingClass getHelpingClass(){
return new HelpingClass();
}
}
并在您的测试中使用@Spy,如下所示:
public class TestValues {
@InjectMocks
@Spy
NameClass names;
@Mock HelpingClass help;
@Test
public void testgetValues() throws Exception
{
doReturn(help).when(names).getHelpingClass();
Mockito.when(help.getJSONFile()).thenReturn(json);
...
}
}
关于java - 模拟方法,但它调用实际方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834738/