Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a very simple class.
C#
public class MyClass
{
    private String MyString;
    private String MyStringB;

    public MyClass()
    {
        MyString = "MyString has been set.";
        MyStringB = SetMyString();
    }

    private String SetMyString()
    { return "My String has been set by the function call."; }
}


which runs a unit test accessing its private members.

C#
[TestClass]
public class MyTestClass
{
    String DesiredOutCome = "My String has been set by the function call.";

    [TestMethod]
    public void TestMyClassConstructor()
    {
        MyClass MyObject = new MyClass();
        PrivateObject obj = new PrivateObject(MyObject);
        var MyOutCome = obj.GetFieldOrProperty("MyStringB");
        Assert.AreEqual(DesiredOutCome, MyOutCome);
    }
    }


Now i need to do a Shim to replace the dependency SetMyString().

C#
String NewDesiredOutCome = "MyString has been set to something different.";

[TestMethod]
public void TestMyClassConstructorWithShim()
{
	using (ShimsContext.Create())
	{
		MyNameSpace.Fakes.ShimMyClass.Constructor = (@this) =>
		{
			var shim = new ShimMyClass(@this)
			{
				SetMyString = () => { return "MyString has been set to something different."; }
			};
		};

		MyClass MyObject = new MyClass();
		PrivateObject obj = new PrivateObject(MyObject);
		var MyOutCome = obj.GetFieldOrProperty("MyStringB");
		Assert.AreEqual(NewDesiredOutCome, MyOutCome );
	};
}


But this fails with
Assert.Are equal failed. Expected <MyString has been set to something different.> Actual: <(Null)>

for some reason, the Shim which should only modify the constructor call, seems to modify the whole class, removing the member variable MyStringB... i cant see any reason it should be null.

What I have tried:

I tried stepping through the debugger, cant figure out why obj.GetFieldOrProperty returns a null to a field which exists, and the other unit test proves it does.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900