简体   繁体   English

如何为特殊的测试用例编写可测试的代码

[英]How to write testable code for a special test case

I have an asynchronous readFile(path, callback) function. 我有一个异步readFile(path,callback)函数。

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? 我如何实现readFile()使其可测试的缓存功能?

你嘲笑原生文件开启者。

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. 或者,您可以公开针对其缓存的变量,然后对其进行修改并进行检查。

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 :) 我可以将一个标志传递给回调(错误,内容,fromMemory),指示它是来自文件系统还是内存:)

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. 可以模拟此检查以在一种情况下返回true而在另一种情况下返回false,并且您可以围绕此检查编写测试。 hope i am making sense here. 希望我在这里有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM