简体   繁体   中英

Is reading csv file from physical path is valid scenario in unit test case ? why?

string _inboundFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\Inbound\CompareDataFile.csv";

var mockReaderStream = new Mock<IReaderStream>();
mockReaderStream.Setup(x => x.CreateStream())
    .Returns(new System.IO.StreamReader(_inboundFilePath));

Here I am dependent on an inbound file to read data from and then perform other function checks. my question is how to avoid this? In this case I am checking data for a particular id that comes in from the csv.

It is not likely to be a good practice because a unit test must be deterministic. It means that whatever the situation, you must be sure that if this test runs, it will do exactly the same than before.

If you read a csv file, the test will depend on the external world. And unfortunately, the external world is not stable. For a start somebody can change the csv file.

That is why it is a better practice to get the csv file stream from a an embedded resource in the assembly instead of getting it from a file on the hard drive.

In addition to the answer from Stephane. I will suggest you:

  1. Put @"\\Inbound\\CompareDataFile.csv" to config file.

  2. Create public property or separate method in the aforementioned class that will be able to retrieve and return the inbound file absolute path (call it GetPath ).

  3. Create UnitTest method that have access to the config file. This TestMethod must read config files, call AppDomain.CurrentDomain.BaseDirectory . So this method could also retrieve the path of inbound file absolute path and after this call GetPath()

  4. Create abstraction (interface or abstract class above Mock - (it's not a mock by the way in the code you've provided, so hard to guess why you call it so)).

  5. Create public method in the aforementioned class that will require an object of the abstraction and call its method ReadFromCsv() .

  6. Create Test class (mock) that will implement this abstraction and will return desired/undesired values when you call it's method ReadFromCsv() .

  7. Finally, test your class.

PS. This is not a strict algorithm of testing the class, you can use it. By what you would like to get from all this seven items is the notion of unit-test-likeness.

Also you do not free your class from config file, so, use this approach to free your class from config: How to mock ConfigurationManager.AppSettings with moq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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