For those who code using Test-Driven Development, creating
the unit test is the key to designing successful software and there are times
when complex logic needs thoroughly tested. To do this I have built some
software to help. It all works through a ReflectionMockingManager class, which
defines the object that will be mocked. Here is a test that can mock the
properties of a class.
Listing 1
[Test]
public void TestUserFieldAccess()
{
User user = new User();
user.Name = "Brian";
ReflectionMock userMock = ReflectionMockingManager.MockObject(user);
FieldDefinition prop = userMock.Field("Name", typeof(string));
Assert.AreEqual("Brian", prop.GetValue < string > (user));
Assert.AreEqual("Ted", prop.MockGetValue < string > (user, "Ted"));
Assert.AreEqual("Jimmy", prop.MockGetValue < string > (user, "Jimmy"));
}
It has some usefulness because you can mock the test values
returned are equal to the value you specify and that value is used in the
business logic to see if the remaining logic works. For instance, you can set
property values even if they are not public "injecting" of a value
into the object. However, when trying to mock a list that was returned from
the database provider, a SQL Exception is thrown because the DAL provider code
is not actually mocked. So the following test fails for that very reason.
Listing 2
[Test]
public void TestGettingUsers()
{
List < User > usersList = new List < User > ();
usersList.Add(new User("Brian", "b@gmail.com"));
usersList.Add(new User("Ted", "t@gmail.com"));
ReflectionMock mock = ReflectionMockingManager.MockObject < UserProvider > ();
UserProvider provider = new UserProvider();
User[]mockedList = mock.Method("GetUsers", typeof(User[])).MockReturnValue <
User[] > (provider, usersList.ToArray());
Assert.IsNotNull(mockedList);
Assert.AreEqual(2, mockedList.Length);
}
This is why something more is needed, above and beyond
simple reflection, because reflection does not have the ability to alter
whether the method runs or not, and setup expectations for the method.