您如何模拟xml以进行单元测试? [英] how do you mock an xml for unit testing?
问题描述
我需要对该GetData方法进行单元测试.
I need to unit testing this GetData method.
public MessageResponse GetData(XmlElement requestElement)
{
MessageResponse MsgResponse = new MessageResponse();
if (requestElement.Attributes["employeeNo"] == null){
MsgResponse.Messages = new List<string>();
MsgResponse.Messages.Add("Attribute employeeNo is missing");
MsgResponse.Error = true;
return MsgResponse;
}
if (requestElement.Attributes["xmlEmployeeName"] == null){
MsgResponse.Messages.Add("Attribute xmlEmployeeName is missing");
MsgResponse.Error = true;
return MsgResponse;
}
return MsgResponse;
}
此方法需要XmlElement参数.我该如何嘲笑它?在我的代码中,我首先创建了一个xmlDocument,然后加载了xml文件.
this method needs a XmlElement parameter. how do I mock it? in my code, I first created a xmlDocument, then load the xml file.
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
requestElement = doc.DocumentElement;
让我测试一下,首先我需要创建一个没有employeeNo的xml文件,创建另一个没有名称的文件,对于其他情况可能还要更多.看起来好像很多工作.有更好的测试方法吗?
for me to test it, first i need to create a xml file without employeeNo, the create antoher one without name, maybe alot more for other scenarios. it just seems like alot work. is there a better way to test it?
我应该使用moq或其他测试框架来简化测试吗?
should I use moq or other testing framework to simplify the testing?
推荐答案
您可以创建要测试的元素,而无需读取文件:
You can just create the element you want to test with, w/o reading a file at all:
var doc = new XmlDocument();
doc.LoadXml("<MyTestElement/>");
var myTestElement = doc.DocumentElement;
myTestElement.Attributes["employeeNo"] = "fakeId";
var response = myTestResponder.GetData(myTestElement);
//assert whatever you need to
注意:每当您发现测试很难编写时,通常这意味着您的类/方法做得太多.
NOTE: every time you find out that the test is too hard to write, usually this means that your class/method does too much.
我认为,与提供的数据相比,您的方法可以验证输入.我建议您抽象化数据读取部分(使用一些xml反序列化器)以填充应用程序所需的数据模型.
I would assume, that your method verifies the input, than does something with the data provided. I would suggest that you abstract the data reading part (using some xml deserializer) to populate the data model you need for your application.
然后对反序列化数据的结果进行验证.像这样:
Then run validation on the result of the deserialized data. Something like:
public MessageResponse GetData(XmlElement requestElement)
{
var data = _xmlDeserializer.Deserialize(requestElement);
var validationResult = _validator.Validate(data);
if (validationResult.Errors.Count > 0)
{
//populate errors
return result;
}
_dataProcessor.DoSomethingWithData(data);
}
看看 FluentValidation ,获得一个不错的验证库.
Take a look at FluentValidation for a nice validation library.
如果您选择上述路线,那么您的测试就会简单得多.
If you go the above route, then your tests will be much simpler.
这篇关于您如何模拟xml以进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!