Checking Junit Mocking File Operations

I have a code similar to the one below that I was asked for by the Junit test. We use Junit, EasyMock and Spring Framework. I have not done many Junit tests, and I have lost a little how I can make fun of below.

Basically, the path to the file, as in the directory in which it will be located, will not exist when I write or run the test on my machine. I am wondering if there is a way to mock the object at a temporary location, since the location at which it will work will be guaranteed to exist and be tested during integration testing.

However, I wonder if it would be even wise to do this or whether it should be tested when it is integrated with the rest of the project, when the catalog really exists.

Any help is appreciated since Junit testing is completely new to me. I looked around, but I can’t understand how to do what I want (maybe a good hint that I should not do this: P).

String fileName = pathToFileName; File file = new File(fileName); if (file.exists()) { FileUtil.removeLineFromFile(file, getValueToRemove(serialNumber)); } 
+4
source share
1 answer

The first option is to insert the file into your class, where you can simply enter the layout directly. Usually the best option, but not always elegant or doable.

I got some mileage from these things by creating a protected wrapper function for problematic objects like this. In the tested class:

 protected File OpenFile(String fileName) { return new File(filename;} 

In the test class:

 File file = EasyMock.createNiceMock(File.class); private MyClass createMyClass() { return new MyClass() { @Override protected File OpenFile(String fileName) { return file; } }; } @Test public testFoo() { EasyMock.expect(file.exists()).andStubReturn(true); //... MyClass myClass=createMyClass(); // ... } 

If you need, you can save the construction parameters (file_name) in this case for verification.

+3
source

Source: https://habr.com/ru/post/1394309/


All Articles