我是TDD开发新手,刚开始使用Nunit 3.7.1,Newtonsoft.Json版本= 10.0.3,C#和。 NET Framework 4.7。在测试方法和测试方法中使用相同的代码
我创造了这个测试来测试反序列化JSON:
[Test]
public void ShouldGenerateBatchExportFile()
{
string json = @"{""ProductionOrderName"": ""proOrd"",""BatchName"": ""batch_01"",""Codes"": [ --- OMITTED FOR BREVETY --- ]}";
string path = @"d:\trzlexportsample.json";
BatchExportFile exportFile = null;
exportFile = JsonConvert.DeserializeObject<BatchExportFile>(json);
BatchExportFile generatedFile = _import.LoadBatchFile(path);
Assert.AreEqual(generatedFile.ProductionOrderName, exportFile.ProductionOrderName);
Assert.AreEqual(generatedFile.BatchName, exportFile.BatchName);
Assert.That(generatedFile.Codes, Has.Count.EqualTo(exportFile.Codes.Count));
Assert.That(generatedFile.Aggregations, Has.Count.EqualTo(exportFile.Aggregations.Count));
for(int index = 0; index < generatedFile.Codes.Count; index++)
{
CodeData gData = generatedFile.Codes[index];
CodeData testData = exportFile.Codes[index];
Assert.AreEqual(gData.CodeId, testData.CodeId);
Assert.AreEqual(gData.Serial, testData.Serial);
Assert.AreEqual(gData.AggregationLevelId, testData.AggregationLevelId);
Assert.AreEqual(gData.CommissioningFlag, testData.CommissioningFlag);
Assert.AreEqual(gData.LastChange, testData.LastChange);
Assert.AreEqual(gData.UserName, testData.UserName);
Assert.AreEqual(gData.Source, testData.Source);
Assert.AreEqual(gData.Reason, testData.Reason);
}
for (int index = 0; index < generatedFile.Aggregations.Count; index++)
{
AggregationData gData = generatedFile.Aggregations[index];
AggregationData testData = generatedFile.Aggregations[index];
Assert.AreEqual(gData.AggregationId, testData.AggregationId);
Assert.AreEqual(gData.Parent, testData.Parent);
Assert.That(gData.Children, Has.Count.EqualTo(testData.Children.Count));
for (int j = 0; j < gData.Children.Count; j++)
{
AggregationChildrenData gChildren = gData.Children[j];
AggregationChildrenData testChildren = testData.Children[j];
Assert.AreEqual(gChildren.Serial, testChildren.Serial);
Assert.AreEqual(gChildren.Serial, testChildren.Serial);
}
}
}
这是方法我测试:
public BatchExportFile LoadBatchFile(string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentNullException(nameof(path));
BatchExportFile exportFile = null;
using (StreamReader file = File.OpenText(path))
{
JsonSerializer serializer = new JsonSerializer();
exportFile = (BatchExportFile)serializer.Deserialize(file, typeof(BatchExportFile));
}
return exportFile;
}
文件D:\trzlexportsample.json
比string json
相同的内容。
我不知道我是否以正确的方式进行测试,因为在测试中我使用的方法大多与方法_import.LoadBatchFile(path)
中的方法相同。
在测试中我有这样的代码:
exportFile = JsonConvert.DeserializeObject<BatchExportFile>(json);
而且在测试方法我有这样的代码:
using (StreamReader file = File.OpenText(path))
{
JsonSerializer serializer = new JsonSerializer();
exportFile = (BatchExportFile)serializer.Deserialize(file, typeof(BatchExportFile));
}
他们大多是相同的。
我这样做的方式是否正确?
换句话说,在测试和测试方法中使用相同的代码是否正确?