1

I have an asynchronous readFile(path, callback) function.

The very first time it reads a file it will read it from the file system. It will save the content into the memory.

Afterwards when the same file is read it will just return the content from memory instead of hitting the file system again.

The problem I'm having is how to test this that mechanism is working in a test suite since there is no way for the method call to know if the content is returned from the file system or memory.

How can I implement readFile() so it's caching feature is testable?

ajsie
  • 77,632
  • 106
  • 276
  • 381

4 Answers4

2

You mock out the native file opener.

pkoch
  • 2,682
  • 1
  • 19
  • 17
  • I should have told you that I don't love to mock external services due to personal reasons. But +1 for recommending a best practice. – ajsie Feb 25 '12 at 05:37
  • I'm against using knives to kill people. But I'm all for using them to cut vegetables. :p What I mean is that using the right tool for the right job can't be wrong. And this is the perfect case for using mocks. – pkoch Feb 25 '12 at 17:07
  • Agreed, mocks are almost always the wrong answer to a problem, but in this case, they're absolutely correct. – Ross Patterson Feb 26 '12 at 16:19
1

Why not read the file using your call, then modify the file, then try and read the file again. If it is the same as the first go, and different from your second then it would work. Alternatively, you could expose the variable that it caches against, and modify that, and check it.

balupton
  • 47,113
  • 32
  • 131
  • 182
  • Presumably you meant "... then modify the **file** ...". Which is a great way to test the routine without having to mock anything out. +1 – Ross Patterson Feb 26 '12 at 16:21
0

Why didn't I thought about this before. I could just pass a flag into the callback(err, content, fromMemory) indicating if it's from file system or memory :)

ajsie
  • 77,632
  • 106
  • 276
  • 381
  • But, but, but ... your entire purpose in writing this test is that you want to verify correct behavior by the routine. And now you're delegating that verification to the routine itself! – Ross Patterson Feb 26 '12 at 16:20
0

At the code level definitely you should have had a check whether the content is there in the cache or not, if not go to the file and read else return from the cache. This check can be mocked to return true in one case and false in another case and you can write a test around this. hope i am making sense here.

raddykrish
  • 1,866
  • 13
  • 15