Mocking in Unit Tests
page 3 of 8
by Brian Mains
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 35197/ 52

Logic Mocking through Reflection Mock

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

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

public void TestGettingUsers()
  List < User > usersList = new List < User > ();
  usersList.Add(new User("Brian", ""));
  usersList.Add(new User("Ted", ""));
  ReflectionMock mock = ReflectionMockingManager.MockObject < UserProvider > ();
  UserProvider provider = new UserProvider();
  User[]mockedList = mock.Method("GetUsers"typeof(User[])).MockReturnValue <
    User[] > (provider, usersList.ToArray());
  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.

View Entire Article

User Comments

No comments posted yet.

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-07-23 5:45:23 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search