我的单元测试方法如下
[Test]
public void TrackPublicationChangesOnCDSTest()
{
//Arrange
// objDiskDeliveryBO = new DiskDeliveryBO();
//Act
var actualResult = objDiskDeliveryBO.TrackPublicationChangesOnCDS();
//Assert
var expectedZipName = 0;
Assert.AreEqual(expectedZipName, actualResult);
}
BO中的实际方法TrackPublicationChangesOnCDS
如下
public int TrackPublicationChangesOnCDS()
{
var resultFlag = -1;
try
{
string pubUpdateFileCDSPath = CommonCalls.PubUpdateFileCDSPath;
string pubUpdateFileLocalPath = CommonCalls.PubUpdateFileLocalPath;
if (File.Exists(pubUpdateFileCDSPath))
File.Copy(pubUpdateFileCDSPath, pubUpdateFileLocalPath, true);
if (File.Exists(pubUpdateFileLocalPath))
{
string[] pubRecords = File.ReadAllLines(pubUpdateFileLocalPath);
var pubRecordsExceptToday = pubRecords.Where(p => !p.Trim().EndsWith(DateTime.Now.ToString("dd/MM/yy"))).ToList();
resultFlag = new DiskDeliveryDAO().TrackPublicationChangesOnCDS(pubRecordsExceptToday);
File.WriteAllText(pubUpdateFileLocalPath, string.Empty);
string[] pubRecordsCDS = File.ReadAllLines(pubUpdateFileCDSPath);
var pubRecordsTodayCDS = pubRecordsCDS.Where(p => p.Trim().EndsWith(DateTime.Now.ToString("dd/MM/yy"))).ToList();
File.WriteAllLines(pubUpdateFileCDSPath, pubRecordsTodayCDS);
}
return resultFlag;
}
catch (Exception)
{
return -1;
}
}
虽然调试调试器到了 string pubUpdateFileCDSPath = CommonCalls.PubUpdateFileCDSPath;
但是CommonCalls.PubUpdateFileCDSPath;
返回空字符串。它应该返回文件路径。当该方法直接调用时,它可以正常工作。当单元测试方法中调用它时,它不起作用。
CommonCalls.PubUpdateFileCDSPath
是定义为下面的静态属性。
public static string PubUpdateFileCDSPath
{
get { return GetXmlConfigValue("PubUpdateFileCDSPath"); }
}
public static string GetXmlConfigValue(string nodeName)
{
var xml = new XmlDocument();
xml.Load(ConfigValuesXml);
var node = xml.SelectSingleNode("JanesOfflineDeliveryService/" + nodeName);
return node != null ? node.InnerText : string.Empty;
}
Configvaluesxml
是XML文件路径。文件的内容为
<JanesOfflineDeliveryService>
<PubUpdateFileCDSPath>D:OfflineDeliveryCDSpub_update.txt</PubUpdateFileCDSPath>
<PubUpdateFileLocalPath>D:pub_update.txt</PubUpdateFileLocalPath>
</JanesOfflineDeliveryService>
在您的测试方案中getxmlConfigvalue(" bubupdatefilecdspath"(不存在,因此返回字符串为空。这就是为什么您应该避免使用静态方法,因为它们不可模拟。解决方法可能是将路径变量传递到方法中。
使用静态依赖性使单位测试代码隔离困难。通过将依赖性提取并将其注入依赖性类别。
public interface ICommonCalls {
string PubUpdateFileCDSPath { get; }
string PubUpdateFileLocalPath { get; }
}
以上接口的实现将包装您的静态调用,或者更好地实现它们。
将重构依赖类以进行依赖性反转。
public class DiskDeliveryBO {
private readonly ICommonCalls CommonCalls;
public DiskDeliveryBO(ICommonCalls common) {
this.CommonCalls = common;
}
//...other code removed for brevity.
}
但是,目标方法还与文件系统等实现问题有很多紧密的耦合。这也应该被抽象并倒出因类别。