I am running a WCF application and need to add some unit tests. Initially I tried JustMock, free version as this is the standard for the company I am at at the moment however the free version does not support system.linq.xml
So, I moved over to Moq and thought that this would work, however the code block below
Mock<IVersionFilter> mock = new Mock<IVersionFilter>();
var message = CreateValidGetProposalListMessage();
var returnValue = XDocument.Parse(GenerateXmlString());
mock.Setup(VersionFilter => VersionFilter.ParseMessage(message)).Returns(returnValue);
Which should mock the result of ParseMessage(...) from this call
public override bool Match(Message message)
{
var doc = ParseMessage(message);
var getProposalList = doc.Descendants(_xmlnsa + MethodConstants.GetProposalList).FirstOrDefault();
if (getProposalList != null)
{
// code ommitted
}
/// Test code ommitted
}
public XDocument ParseMessage(Message message)
{
XDocument doc = XDocument.Parse(message.ToString());
return doc;
}
public Message CreateValidGetProposalListMessage()
{
var p = new getProposalList
{
Code = "xxxx"
};
var message = Message.CreateMessage(MessageVersion.Soap11, "getProposalList xmlns=\"http://xxx\">", p);
return message;
}
I cant see what I have missed and would be grateful if someone could help me progress this issue forward.
Thanks
The setup looks mostly ok. I suspect your problem is that setup isn't being invoked at all because of argument equality.
mock.Setup(VersionFilter => VersionFilter.ParseMessage(message)).Returns(returnValue);
This is saying that ParseMessage
invoked with something that equals message
will return returnValue
. If Message
is a class this will only work if Message
implements it's own Equals
method.
As mentioned in my OP comment, start with the basics. Ensure that the setup is being invoked first:
mock.Setup(VersionFilter => VersionFilter.ParseMessage(It.IsAny<Message>())).Returns(returnValue);
Once you've got that working, tune it to suit the test case. You can either implement an Equals
method for the Message
type (Fody would be my suggestion if you want to this), or match it another way via It.Is<Message>(message => match conditions)
.
You have created a mock of IVersionFilter
with this line
Mock<IVersionFilter> mock = new Mock<IVersionFilter>();
But I would expect to see a class that takes a IVersionFilter
in its constructor. You would then do
var myTestClass = new TestClass(mock.Object)
Then when the test class uses the functionality in IVersionFilter
it uses the mocked one
Just to clarify, TestClass would be something like
public class TestClass(IVersionFilter filter)
{
public void DoSomething()
{
filter.DoSomething();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.