3

I'm working on a class that should manipulate files.

Its interface has a Open(string filename) method, and various other methods to retrieve and manipulate the contents.

Is it ok to call the open method before calling the method I'm trying to test?

On one side, this documents the fact that the open method should be called before any other method.

On the other hand, I'm worried about the effectiveness of those tests as, if the Open method stops working, all tests would fail without actually reporting a failure of the method they should test.

Things I considered:

Using reflection while testing to put the object into a known "workable" state, without calling the open method (complex and hard to maintain)

Using a static construction method that creates the object and then opens it, returning the working object (but there should also be an option to have the object in a "closed" state, plus this doesn't avoid calling the open method, it just hides it)

BgrWorker
  • 1,694
  • 2
  • 9
  • 14
  • Read up on RAII (Resource Acquisition Is Initialization) https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization – RvdK Jul 25 '16 at 11:44

1 Answers1

4

Based on what you describe, then, yes, it is a necessary evil to call the open method even though, as you say, a failure of open will inappropriately show failures of all the dependent tests.

However, I would recommend a rather different approach. Any classes that have to go to "bare metal" (i.e. touch system resources) should strive to be conduit-only classes, i.e. do the absolute minimum to handle the resource. In your question you actually make the clear delineation: your methods "... retrieve and manipulate the contents." So what I am suggesting is that you have a FileSystemProvider to retrieve the contents and a separate FileSystemManipulator to manipulate the contents. The latter will take a FileSystemProvider as an injected dependency, thus making it a simple task to mock a FileSystemProvider when you are unit-testing FileSystemManipulator, and rendering your question moot.

Of course, testing FileSystemProvider will need to touch real files but its methods should be so simple and straightforward as to almost not need unit tests. (One could argue that they, in fact, would no longer be unit tests because they touch system resources; rather they are then developer-level integration tests, and you could then be a little bit lax with applying the stringent guidelines of unit tests to them.)

Michael Sorens
  • 1,346
  • 8
  • 11