[英]How to mock a file in root folder to be modified
For some reason, I have a path (//what/ever) stored in a private variable in a class where the file is modified. 由于某种原因,我在修改文件的类中的私有变量中存储了一个路径(//什么/曾经)。 So, when I test it, it tries to modify the file, but, since the file is not there, an exception is thrown.
因此,当我对其进行测试时,它将尝试修改文件,但是由于文件不存在,因此引发了异常。
Of course, for unit testing, I don't want to create that file in the filesystem. 当然,对于单元测试,我不想在文件系统中创建该文件。
Is there a way to mock that very file and force the machine to write in //my/folder instead of //what/ever? 有没有一种方法可以模拟该文件并强制机器以// my / folder而不是// what / ever进行写入?
Mocking the file itself might be difficult. 模拟文件本身可能很困难。 Unless, you abstract away your file handling into some interface that you manage and can inject a mock implementation during the test run.
除非,否则将文件处理抽象到您管理的某个接口中,并可以在测试运行期间注入模拟实现。 Another approach would be to expose the file path such that you can change it as part of your test setup code.
另一种方法是公开文件路径,以便您可以将其更改为测试设置代码的一部分。
Yet another approach involves JUnit 4. In JUnit 4, you have the ability to manage temporary files and folders in your test runs. 另一个方法涉及JUnit4。在JUnit 4中,您可以在测试运行中管理临时文件和文件夹。 It will cleanup any new files or folders you create.
它将清除您创建的所有新文件或文件夹。
It can be done like so: 可以这样完成:
public class MyFileTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void testSomething() throws IOException {
File tempFile = testFolder.newFile("myfile");
I think something like this would allow you to create the actual file so your code can modify it, hence not blowing up. 我认为这样可以让您创建实际的文件,以便您的代码可以对其进行修改,因此不会崩溃。 You might want to consider exactly the scope of your test in terms of:
您可能需要从以下方面考虑测试范围:
Answering some of these questions might move you in the right direction of exactly what kind of test you should write and what refactoring you may need to do to facilitate the test requirements. 回答其中的一些问题可能使您朝正确的方向前进,即应该编写哪种测试以及为满足测试要求可能需要进行的重构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.