Jean Pougetoux
Jean Pougetoux

Reputation: 41

Modifying mock property which has been set up

I'm going to simplify a bit the problem:

In my tests, I use a mocked object (I mocked it because it calls a bdd) which I give in parameters to a method of another object (not mocked) whose purpose is to modify a property of this mocked object.

ModifyingClass myModifyingClass = new ModifyingClass();
Mock<ToModifyClass> mockedClass = new Mock<ToModifyClass>();
mockedClass.Setup(mc => mc.name).Returns("Test1");
myModifyingClass.modify(mockedClass.Object);

The method modify then try to set the property name of the mocked object, but it won't work, so maybe it's the normal behavior but I really need to test if all of this work and if the method modify set the property as I want.

Upvotes: 3

Views: 4226

Answers (2)

Nkosi
Nkosi

Reputation: 247531

As mentioned in the comments you need to setup the mocked class differently in order to retain the values passed to properties.

Reference Moq - Quickstart

Stub all properties on a mock (not available on Silverlight):

mock.SetupAllProperties();

The example test provided would then look like...

//Arrange
var myModifyingClass = new ModifyingClass();
var mockedClass = new Mock<ToModifyClass>();
mockedClass.SetupAllProperties(); //<-- this will allow property changes to be retained.
var model = mockedClass.Object;
//set the property now that it can be set
model.name = "Test1";
var expected = "expected value here";

//Act
myModifyingClass.modify(model);

//Assert
var actual = model.name;
Assert.AreEqual(expected, actual);
//... other assertions

Upvotes: 1

Janis S.
Janis S.

Reputation: 2626

In Moq one would need to setup the getter.

mockedClass.SetupGet(mc => mc.name).Returns("Test1");

Upvotes: 0

Related Questions