Unit Testing File Modifications

后端 未结 6 1021
轮回少年
轮回少年 2020-12-29 05:47

A common task in programs I\'ve been working on lately is modifying a text file in some way. (Hey, I\'m on Linux. Everything\'s a file. And I do large-scale system admin.)

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 06:17

    When I touch files in my code, I tend to prefer to mock the actual reading and writing of the file... so then I can give my classes exact contents I want in the test, and then assert that the test is writing back the contents I expect.

    I've done this in Java, and I imagine it is quite simple in Python... but it may require designing your classes/functions in such a way that it is EASY to mock the use of an actual file.

    For this, you can try passing in streams and then just pass in a simple string input/output stream which won't write to a file, or have a function that does the actual "write this string to a file" or "read this string from a file", and then replace that function in your tests.

提交回复
热议问题