Goal
Create a method that first creates a file and then deletes it. Sounds pretty useless but it makes a good example.
This tutorial is written in C#. You can use any mock object and unit test frameworks of your choice. In this example we're using
Rhino Mocks and
MbUnit v3.
Steps
- Create sample project.
- Create unit test.
- Create method under test.
Create sample project.
- Create new Class Library project and name it SysWrapSample.
- Add reference to your mock object framework. If you're using Rhino mocks, click on Browse tab in Add Reference dialog and reference to Rhino.Mocks.dll.
- Add reference to your unit test framework. If you're using MbUnit v3, click on .NET tab in Add Reference dialog and select Gallio and MbUnit.
- Add the last reference to SystemWrapper.dll.
- Rename Class1 class into FileInfoSample.
- Add using statements for SystemWrapper.IO, MbUnit.Framework, and Rhino.Mocks. Your class should look like this:
using SystemWrapper.IO;
using MbUnit.Framework;
using Rhino.Mocks;
namespace SysWrapSample
{
public class FileInfoSample
{
}
}
Create unit test.
Add FileInfoSampleTest class.
public class FileInfoSampleTest
{
}
Add the test method.
[Test]
public void Check_that_FileInfo_methods_Create_and_Delete_are_called()
{
// Add mock repository.
IFileInfoWrap fileInfoRepository = MockRepository.GenerateMock<IFileInfoWrap>();
IFileStreamWrap fileStreamRepository = MockRepository.GenerateMock<IFileStreamWrap>();
// Create expectations
fileInfoRepository.Expect(x => x.Create()).Return(fileStreamRepository);
fileStreamRepository.Expect(x => x.Close());
fileInfoRepository.Expect(x => x.Delete());
// Test
new FileInfoSample().CreateAndDeleteFile(fileInfoRepository);
// Verify expectations.
fileInfoRepository.VerifyAllExpectations();
fileStreamRepository.VerifyAllExpectations();
}
Create method under test.
Add CreateAndDeleteFile method to FileInfoSample class.
public void CreateAndDeleteFile(IFileInfoWrap fi)
{
IFileStreamWrap fs = fi.Create();
fs.Close();
fi.Delete();
}