简体   繁体   中英

How to Unit Test a method that has fileName as a Parameter

I have the following method:

public static IEnumerable<Customer> GetStuff(string fileName,int filterValue)

How would you unit test this? Obviously, my problem is with the fileName parameter.

Thank you!

To make another answer-attempt: I guess theJollySin hit the problem but did not explain enough (IMHO)

You seem to take the fileName and hit the systems file-system in your GetStuff method. And that is the problem if you want to unit-test it. You have to push the things you do with the file-system (opening/creating/readin files, etc.) into a interface or something and then mock this. A example might be:

public interface IMyFileIO
{
    public byte[] ReadFromFile(int bytes); // whatever
}

public static IEnumerable<Customer> GetStuff(IMyFileIO file, int filterValue)
{
}

And then use mocking-frameworks (like for example MOQ ) to mock IMyFileIO :

[Test]
public void TestFileIO()
{
   var mock = new Mock<IMyFileIO>();
   mock.Setup(foo => foo.ReadFromFile(2)).Returns(new byte[]{2,3});

   var myResult = MyClass.GetStuff(mock.Object, 10);
   Assert. // <- what you need to check
}

Please note that depending on what your are doing, chances are high that there is already a interace/base-class providing the functionality you need (StreamWriter, whatever)

I'd personally go for changing a method into something more general like

public static IEnumerable<Customer> GetStuff(Stream dataStream,int filterValue)

This would give you the ability to use mock stream or MemoryStream instead of FileStream to fetch data and unit test it correctly. Also, I personally suggest making methods as general as they can be (Stream vs. filePath is a good example).

I am assuming the issue is that the method goes out to the file system to fetch the file? I would as a precondition to the test actually create a file for your method to get...You may then pass in the newly created file name to your test. It becomes an integration test at that point, but it's still valid for testing purposes. It's just not a "pure" unit test

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