I wrote a simple class to manage business objects.
class Manager
{
string[] GetNames();
BObject GetObject(string name);
void Saveobject(BObject obj);
}
It serializes /deserializes the objects as files on a local disk. I wrote Unit tests for the class and run them. That was fine so far. The problem happens when my test were run on build server because of file access permission I was not allowed to write files on the server. It’s obvious I cannot test that way.
I think how to unit test this. One approach I can see is to extract an interface and creat a mock object for testing. But I want to test the class itself. How can I do it?
The class presumably calls file system operations
File.OpenRead(),File.OpenWrite()etc. (I assume that this is C# due to the camel casing.) Then, you could create an interface for those operations, e.g.:and make the constructor of
Managertake an instance ofIFileSystem. Then, write a (non-mock) class that implementsIFileSystemby calling the actualFile.OpenRead()andFile.OpenWrite()methods and use this one in the production code. In the tests, you use a mock framework, as mentioned by @Digger (my personal preference is Moq, but I haven’t tried Rhino Mocks, so I have nothing negative to say about it) to mock outIFileSystemand use the mock to verify that the methods were called with the correct serialized data.EDIT: Per request, an example in NUnit with Moq (I don’t have an IDE here, so it’s untested; feel free to correct it):