问题
I have a mocked object in my unit tests that has a property. At a certain point in my test, the code blows up because that property returns null, even though it was just set to a non-null value. I have tried using SetupAllProperties()
, SetupProperty()
with just that property, and explicitly building SetupGet
and SetupSet
setAlignment = new Alignment();
mockSetAlignmentRandomizer.SetupAllProperties();
mockSetAlignmentRandomizer.SetupSet(r => r.SetAlignment = It.IsAny<Alignment>()).Callback<Alignment>(value => setAlignment = value);
mockSetAlignmentRandomizer.SetupGet(r => r.SetAlignment).Returns(() => setAlignment);
mockSetAlignmentRandomizer.Setup(r => r.Randomize()).Returns(mockSetAlignmentRandomizer.Object.SetAlignment);
mockSetLevelRandomizer.Setup(r => r.Randomize()).Returns(mockSetLevelRandomizer.Object.SetLevel);
mockAlignmentGenerator.Setup(f => f.GenerateWith(mockSetAlignmentRandomizer.Object)).Returns(() => mockSetAlignmentRandomizer.Object.SetAlignment);
mockAlignmentGenerator.Setup(f => f.GenerateWith(mockAnyAlignmentRandomizer.Object)).Returns(() => new Alignment());
The problem occurs with the AlignmentGenerator
when it gets here:
do setAlignmentRandomizer.SetAlignment = alignmentGenerator.GenerateWith(anyAlignmentRandomizer);
while (allowedAlignments.Contains(setAlignmentRandomizer.SetAlignment.ToString()) == false);
Even though I can confirm that the generator spits out a new Alignment
object, the property on setAlignmentRandomizer
is always null
, which makes the whole evaluation throw an unexpected error. Yes, I have also confirmed that the allowedAlignments
collection (created elsewhere in the code) is also not null. What am I doing wrong here?
回答1:
And the answer is that I am a dork. The setup for this whole test class is very convoluted, unfortunately, and in the midst of the chaos, I missed that I was accidentally newing up that mock more than once - I properly set up the properties the first time, but then newed it up the second time, and lost all that setup.
来源:https://stackoverflow.com/questions/31431698/moq-does-not-preserve-property-values