While I was experimenting to resolve a different situation with Moq, I attempted to use SetupSet to resolve. This uncovered another potential problem.
When I use SetupSet on a property along with a Setup on a Method, Moq seems to 'forget' that the Setup on the Method has been done.
Here is sample code, very simple:
public class Prancer
{
public Prancer(bool pIsMale)
{
IsMale = pIsMale;
ExecuteMe();
}
private bool _IsMale;
public virtual bool IsMale
{
get { return this._IsMale; }
private set { this._IsMale = value; }
}
private bool _Antlers;
public virtual bool Antlers
{
get { return this._Antlers; }
set
{
this._Antlers = value;
}
}
public virtual void ExecuteMe()
{
throw new Exception("Why am I here?");
}
}
Here are the unit tests:
public class PrancerTests
{
[Fact]
public void Antlers_NoSetup()
{
// Arrange
// create mock of class under test
var sut = new Mock<Prancer>(true) { CallBase = true };
sut.Setup(x => x.ExecuteMe()); // nullify
// Act
sut.Object.Antlers = true;
// Assert
sut.VerifySet(x => x.Antlers = true);
}
[Fact]
public void Antlers_SetupProperty()
{
// Arrange
// create mock of class under test
var sut = new Mock<Prancer>(true) { CallBase = true };
sut.SetupProperty(x => x.Antlers, false);
sut.Setup(x => x.ExecuteMe()); // nullify
// Act
sut.Object.Antlers = true;
// Assert
sut.VerifySet(x => x.Antlers = true);
}
[Fact]
public void Antlers_SetupSet()
{
// Arrange
// create mock of class under test
var sut = new Mock<Prancer>(true) { CallBase = true };
sut.SetupSet(x => x.Antlers = true);
sut.Setup(x => x.ExecuteMe()); // nullify
// Act
sut.Object.Antlers = true;
// Assert
sut.VerifySet(x => x.Antlers = true);
}
}
The unit test where I use SetupSet reports the Exception ("Why am I here?") thrown in method ExecuteMe() which proves that the method ExecuteMe() executed even when there was a Setup(x => x.ExecuteMe()) to prevent it. The other two unit tests pass (and apparently do not execute ExecuteMe()).
I even attempted to put a Callback on the Setup for ExecuteMe(), but same result. I also reversed the order (in code) of the Setup and SetupSet, to no avail.
Any thoughts why the SetupSet could have affected the method Setup?