1. Public not enough for mocking a class, needs to be virtual. Mocking
interfaces is sooooo much more easier than mocking classes; I never
mock classes, not worth the headache.
2. I'm still not sure you want to mock that, as it's part of the class
you're trying to test, usually it's best to leave private methods
below because it's an implementation detail private to the class. If
your test digs into the private parts of a class the test/class will
be very brittle... better to try and see your class as a complete
object and only mock the dependencies of the class, not its private
methods.
3.Too optimistic, just creating a mock doesn't mean it get used, you
need to pass it to something, whether that's the class itself (usual
way) or to some sort of Service Locator or IoC container.
4. Note in my test below I don't mock WorkProcess at all... that's
kind of what I was getting at
5. I've removed the dependency on DAL by passing in an IDataProvider
explicitly, your next question might be that in production you want it
to access the DAL, in which case there are several possibilities
including "poor man's dependency injection" where you have another
constructor used only in production which uses DAL to populate the
dependency. Or you could use an IoC container...
This is roughly what I'd do (complete example, note no private accessor needed):
public interface IDataProvider
{
Guid ReturnGUIDFromIntegerMapping(int id);
string ReturnConnectionStringFromIntegerMapping(int id);
}
public class WorkProcess
{
public struct TargetDataSetStruct
{
public Guid DataSet_GUID;
public string ConnectionString;
}
public TargetDataSetStruct TargetDataSet
{
get;
private set;
}
public int DataSet_ID
{
get;
set;
}
private IDataProvider dp;
public WorkProcess(IDataProvider dp)
{
this.dp = dp;
}
internal void RunChecks()
{
TargetDataSet = FindDataSetInDatabaseRegister(DataSet_ID, dp);
}
internal TargetDataSetStruct FindDataSetInDatabaseRegister(int
DataSet_ID, IDataProvider dp)
{
TargetDataSetStruct tds = new TargetDataSetStruct();
tds.DataSet_GUID = dp.ReturnGUIDFromIntegerMapping(DataSet_ID);
tds.ConnectionString =
dp.ReturnConnectionStringFromIntegerMapping(DataSet_ID);
return tds;
}
public void ProcessFile()
{
RunChecks();
}
}
[TestClass()]
public class WorkProcessTest
{
[TestMethod()]
public void ProcessFileShouldPopulateDataSetGuid()
{
//Arrange
IDataProvider mockDP = MockRepository.GenerateMock<IDataProvider>();
WorkProcess target = new WorkProcess(mockDP);
int id = 5;
target.DataSet_ID = id;
Guid expected = Guid.NewGuid();
mockDP.Stub(x => x.ReturnGUIDFromIntegerMapping(id)).Return(expected);
//Act
target.ProcessFile();
//Assert
Assert.AreEqual(expected, target.TargetDataSet.DataSet_GUID);
}
}
2009/10/20 Chris <
chris.m...@gmail.com>