我的Moq正在返回我不期望的数据。
var artist = new Artist();
artist.Id = "4576";
var deserializer = Mock.Of<IXmlDeserializer<Album>>(
d => d.Deserialize("foo").Artist == artist);
Assert.IsNull(deserializer.Deserialize(null));
上述测试失败。
真正令人费解的是,模拟会返回模拟,但
Assert.AreEqual("4576", deserializer.Deserialize(null).Artist.Id)
返回true。
就好像我的模拟器为未指定的参数返回的“默认”(在这种情况下为null)在某种程度上受到我用“foo”调用时返回的内容的影响。
答案 0 :(得分:1)
你可以写:
var artist = new Artist { Id = "4576" };
var mock = new Mock<IXmlDeserializer<Album>>();
mock.Setup(x => x.Deserialize(It.Is<string>(i => i == "foo"))).Returns(new Album() { Artist = artist });
var deserializer = mock.Object;
Assert.IsNull(deserializer.Deserialize(null));
Assert.IsNotNull(deserializer.Deserialize("foo"));
或者使用Mock.Of()语法,上面将是:
var artist = new Artist { Id = "4576" };
var deserializer = Mock.Of<IXmlDeserializer<Album>>(d => d.Deserialize(It.Is<string>(i => i == "foo")) == Mock.Of<Album>(album => album.Artist == artist));
Assert.IsNull(deserializer.Deserialize(null));
Assert.IsNotNull(deserializer.Deserialize("foo"));
Assert.AreEqual("4576", deserializer.Deserialize("foo").Artist.Id);