user3099140
user3099140

Reputation:

Why is my Moq not returning null?

My Moq is returning data I don't expect.

var artist = new Artist();
artist.Id = "4576";
var deserializer = Mock.Of<IXmlDeserializer<Album>>(
    d => d.Deserialize("foo").Artist == artist);
Assert.IsNull(deserializer.Deserialize(null));

The above test fails.

The really puzzling thing is that the mock returns a Mock but that

Assert.AreEqual("4576", deserializer.Deserialize(null).Artist.Id)

returns true.

It's as if the "default" returned by my mock for an unspecified argument (in this case null) was somehow influenced by what I told it to return when called with "foo".

Upvotes: 1

Views: 79

Answers (1)

Chris
Chris

Reputation: 2019

You can either write:

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"));

Or using the Mock.Of() syntax the above would be:

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);

Upvotes: 1

Related Questions