Skip to content

Instantly share code, notes, and snippets.

@killnine
Created December 10, 2013 18:29
Show Gist options
  • Save killnine/7895536 to your computer and use it in GitHub Desktop.
Save killnine/7895536 to your computer and use it in GitHub Desktop.
Testable factory
/*
NEW STRUCTURE OF THE FACTORY
- No longer static
- Uses interface so we can mock response
*/
public interface IDriverFactory { IDriver CreateDriver(DriverType driverType, string ip); }
public class DriverFactory : IDriverFactory
{
public IDriver CreateDriver(DriverType driverType, string ip)
{
//Do some work here to create driver
}
}
/*
SYSTEM UNDER TEST (sut)
- Uses IDriverFactory instance to generate driver
- We can test this now
*/
public class IOTest
{
IDriver _driver;
public IOTest(IDriverFactory driverFactory, DriverType driverType, string ip)
{
_driver = driverFactory.CreateDriver(driverType, ip);
.
.
.
}
public void Execute()
{
_driver.ReadData();
.
.
.
}
}
/*
NUNIT TEST FIXTURE
- Creates Mock IDriver/IDriverFactory
- Allows us to control the response of a mock driver,
testing the Execute method's logic in a very controlled way
*/
[TestFixture]
public class SomeTestClass()
{
[Test]
public void should_create_test_with_mock_driverfactory()
{
//Arrange
DriverType testType = DriverType.S71200;
string ipAddress = "127.0.0.1";
IDriver mockDriver = MockRepository.GenerateMock<IDriver>();
Expect.Call(mockDriver.ReadData()).Return(new byte[] { 0,1,2,3,4 });
IDriverFactory mockFactory = MockRepository.GenerateMock<IDriverFactory>();
Expect.Call(mockFactory.CreateDriver(testType, ipAddress)).Return(mockDriver);
IOTest sut = new IOTest(mockFactory, testType, ipAddress);
//Act
sut.Execute();
//Assert
/* Assert methods in driver were called, or the state of some properties of IOTest (not written here) */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment