Below is my test class. In which I mock File class for 2 times. but it is giving error at second mock of File class.
public class MyClass {
public void myMethod() {
String filePath = "";
filePath = Utility.getFilePath();
File jsonfile = new File(filePath);
if (!jsonfile.exists()) {
String newXmlPath = filePath.replace(".json", ".xml");
File xmlFile = new File(newXmlPath);
if (xmlFile.exists()) {
try(InputStream inputStream = new FileInputStream(xmlFile)) {
// file operation
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
} else {
if (jsonfile.exists()) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(jsonfile);
} catch (FileNotFoundException e) {
}
DataInputStream dis = new DataInputStream(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dis));
// BufferedReader operation
}
}
}
}
public class MyClassTest {
MyClass myClass = new MyClass();
@Test
public void myMethodTest() {
new MockUp<Utility>() {
@Mock
public String getFilePath() {
return "src/test/resources/file.json";
}
};
new MockUp<FileInputStream>() {
@Mock
public void $init() {
}
};
new MockUp<File>() {
private String name;
@Mock
public void $init(String name) {
this.name = name;
}
@Mock
boolean exists() {
if(this.name.contains(".json")) {
return false;
} else {
return true;
}
}
};
myClass.myMethod();
// Line no - 53
new MockUp<File>() {
private String name;
@Mock
public void $init(String name) {
this.name = name;
}
@Mock
boolean exists() {
if(this.name.contains(".json")) {
return true;
} else {
return false;
}
}
};
new MockUp<BufferedReader>() {
@Mock
String readLine() throws IOException {
return null;
}
};
myClass.myMethod();
}
}
Now, every time I run this test it is giving below error.
java.lang.NullPointerException
at java.base/java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.base/java.io.UnixFileSystem.hasBooleanAttributes(UnixFileSystem.java:194)
at java.base/java.io.File.isDirectory(File.java:867)
at java.base/java.net.URL.openStream(URL.java:1325)
at java.base/java.lang.ClassLoader.getResourceAsStream(ClassLoader.java:1764)
at com.testing.code.MyClassTest$123.<init>(MyClassTest.java:53)
at com.testing.code.MyClassTest.myMethodTest(MyClassTest.java:53)
I don’t know what I am doing wrong.
I want to know can we mock same class in same test case multiple times. And If yes then what are the things we need to take care of and If no then what are other alternatives to resolve this problem?
Also, I don’t want to use Mockito, PowerMockito like frameworks and don’t want to use actual file to in this test case.
Thank you in advance.
harshil-padasala is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.