4

I have a piece of code similar to the below that I have been asked to Junit test. We are using Junit, EasyMock and Spring Framework. I've not done much Junit testing, and am a bit lost as to how I can mock the below.

Basically the path to the file as in the directory it will be in, won't exist when I'm writing or running the test on my machine. I'm wondering is there a way to mock the object to a temporary location as the location it will actually run with is guaranteed to exist and be tested during integration testing.

However I'm wondering would it even be wise to do so or should this be tested when it is integrated with the rest of the project when the directory will actually exist.

Any help appreciated, as Junit testing is completely new to me. I've looked around but can't see how to do what I want (might be a good hint that I shouldn't be doing it :P).

String fileName = pathToFileName;

File file = new File(fileName);

if (file.exists()) {

    FileUtil.removeLineFromFile(file, getValueToRemove(serialNumber));
}
IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
brim4brim
  • 163
  • 1
  • 7

1 Answers1

3

First option is to inject the file into your class where you can just inject the mock directly. Usually the better option, but not always elegant or feasible.

I've gotten some mileage out of these things by creating a protected wrapper function for problematic objects such as this. In your class under test:

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 off the construction parameters (fileName) in this case for validation.

Nialscorva
  • 2,924
  • 2
  • 15
  • 16