chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male

Verify private/protected property was set from constructor

+3 votes

How can I test the protected property was correctly initialized in constructor?

Code looks as follows:

public class ClassUnderTest
{
    protected List<Update> Updates { get; }

	public ClassUnderTest(string email)
	{
	    Updates = StaticDatabaseContext.Updates.Where(update => update.email.Equals(email)).ToList();
	}
}

Then the test code looks as follows:

[Test]
public void UpdatesAreInitializedCorrectlyInConstructor()
{
    var updatesTable = Isolate.Fake.Instance<Table<Updates>>();
    Isolate.WhenCalled(() => StaticDatabaseContext.Updates).WillReturn(updatesTable);

    var updates = new List<Updates> { update1, update2 };
    Isolate.WhenCalled(() => updatesTable).WillReturnCollectionValuesOf(updates.AsQueryable());

    var target = new ClassUnderTest("user@email.com");

    // throws an error
    Isolate.Verify.NonPublic.Property.WasCalledSet(target, "Updates").WithArgument(new List<Updates> { update1 });
}

My Isolate.Verify throws an error:

TypeMock.TypeMockException : 
*** Cannot verify methods that were not faked. Either fake the method's class, or use WhenCalled

 

Problem here is, that Isolate.Verify.NonPublic can work only with fakes 

  1. so either target have to be faked
  2. or Updates set property have to be faked (via Isolate.NonPublic.Property.WhenSetCalled)

 

Regarding 1.

While I am creating new instance of ClassUnderTest in test code, Isolate.Fake.NextInstance does not work.

 

Regarding 2.

While the Updates property is not static Isolate.NonPublic.Property.WhenSetCalled(typeof(ClassUnderTest), "Updates").IgnoreCall() cannot be used.

Also Isolate.NonPublic.Property.WhenSetCalled(target, "Updates").IgnoreCall() cannot be used, becase target has already been created and Updates has already been set in constructor.

 

Is there a way how can I verify my property has been initialized correctly in the constructor? 

asked Dec 21, 2017 by Ctvt (2,780 points)
edited Dec 21, 2017 by Ctvt

1 Answer

0 votes
 
Best answer

Hi Milan,

you can extract the property if it has a getter (which in this case it does):

var updates = Isolate.Invoke.Method(target, "get_Updates");

and assert against it, for example:

Assert.AreEqual(updates[0],update1);

Is this what you had in mind?

answered Dec 21, 2017 by Raphy (3,840 points)
selected Jan 3 by Ctvt
This is what I was looking for. Thanks!
...