Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Last active December 26, 2015 08:58
Show Gist options
  • Select an option

  • Save jarrettmeyer/7125564 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/7125564 to your computer and use it in GitHub Desktop.
public interface IWhateverDataTableProvider
{
DataTable GetData();
}
public class WhateverDataTableProvider : IWhateverDataTableProvider
{
public DataTable GetData()
{
// put all that hard-coded, hard to test stuff here...
// copy-paste...
return dataTable;
}
}
public interface IWhateverDataTableProviderFactory
{
IWhateverDataTableProvider CreateProvider();
}
public class WhateverDataTableProviderFactory : IWhateverDataTableProviderFactory
{
private static IWhateverDataTableProviderFactory instance;
public IWhateverDataTableProviderFactory Instance
{
get
{
if (instance == null)
instance = new WhateverDataTableProviderFactory();
return instance;
}
set { instance = value; }
}
public IWhateverDataTableProvider CreateProvider()
{
return new WhateverDataTableProvider();
}
}
public interface IC
{
void DoSomething();
}
public class C : IC
{
public void DoSomething()
{
// ha!
}
}
public interface ICFactory
{
IC Create();
}
public class CFactory : ICFactory
{
private static ICFactory instance;
public static ICFactory Instance
{
get
{
// If no instance has previously been defined, then
// create a new factory.
if (instance == null)
instance = new CFactory();
return instance;
}
// Putting a set accessor here allows us to put in a
// stub at unit test time.
set { instance = value; }
}
public IC Create()
{
return new C();
}
}
public class MockCFactory : ICFactory
{
private readonly Mock<ICFactory> mock;
public MockCFactory()
{
// Create your mock and setups here.
mock = new Mock<ICFactory>();
mock.Setup(x => x.Create()).Returns(new C());
}
public IC Create()
{
return mock.Object.Create();
}
}
// Then, somewhere in a test...
[SetUp]
public void BeforeEachTest()
{
// For purposes of these tests, use our mock factory instead of the real one.
CFactory.Instance = new MockCFactory();
}
[TearDown]
public void AfterEachTest()
{
// Reset the factory back to its default behavior.
CFactory.Instance = null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment