帮助进行单元测试C#代码 [英] Help with unit testing c# code
本文介绍了帮助进行单元测试C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个dll来监视文件夹,拾取xml文件并将内容上载到数据库中.如果存在错误或异常,则将xml文件移动到错误文件夹,否则将其删除.我迷失了对其进行单元测试.有人可以帮我吗?
I have a dll to monitor a folder, pick up xml files and upload the contents into a database. If there is an error or exception the xml file is moved to an error folder, otherwise it is deleted. I am lost unit testing it. Could somebody help me with this please?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TryUnitTesting
{
[XmlRootAttribute("HouseCouncilTaxDetails")]
public class HouseCouncilTaxDetails
{
[XmlElement(typeof(HouseDetails), ElementName = "House"),
XmlElement(typeof(CouncilTaxDetails), ElementName = "CouncilTax")]
public System.Collections.ArrayList HouseCouncilTaxList;
HouseCouncilTaxDetails()
{
}
}
public class HouseDetails
{
[XmlAttribute()]
public String HOUSENAME;
[XmlAttribute()]
public String POSTCODE;
}
public class CouncilTaxDetails
{
[XmlAttribute()]
public String PAYMENTDATE;
[XmlAttribute()]
public String AMOUNT;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Collections;
using Logging;
namespace TryUnitTesting
{
public class FileManager
{
//private string _logFileName = "";
private string _xmlFileDirectory = "";
private string _errorFileDirectory = "";
private string _file = "";
private ArrayList _errorStr;
private int _iNoOfRecordsExported = 0;
private int _iTotalNoOfRecords = 0;
private string _connectionString = "";
private Logging.Log _logger;
public FileManager(Logging.Log logger)
{
_logger = logger;
}
#region "(Public) ProcessFiles Procedure"
public void ProcessFiles(string strDirectory, string strxmlFileDirectory, string strErrorFileDirectory, string strConnectionString)
{
// process all files in the directory
System.IO.DirectoryInfo diDirInfo;
try
{
_logger.RecordMessage("ProcessFiles: Getting list of files", Log.MessageType.Info);
diDirInfo = new System.IO.DirectoryInfo(strDirectory);
System.IO.FileInfo[] fiArray = diDirInfo.GetFiles("*.xml");
if (fiArray != null && fiArray.Length > 0)
{
_logger.RecordMessage("ProcessFiles: " + fiArray.Length.ToString() + " files retrieved", Log.MessageType.Info);
foreach (System.IO.FileInfo fi in fiArray)
{
_logger.RecordMessage("ProcessFiles: File" + fi.FullName, Log.MessageType.Info);
if (System.IO.File.Exists(fi.FullName))
{
_logger.RecordMessage("ProcessFiles: File exists : " + fi.FullName, Log.MessageType.Info);
if (!ProcessIndividualFile(fi.FullName, strxmlFileDirectory, strErrorFileDirectory, strConnectionString))
{
_logger.RecordMessage("ProcessFiles: Failed to process individual file. Exiting", Log.MessageType.Failure);
//Exit For
}
}
else
{
_logger.RecordMessage("ProcessFiles: File doesn't exist: " + fi.FullName, Log.MessageType.Error);
}
}
}
}
catch (Exception ex)
{
_logger.RecordMessage(ex, Log.MessageType.Error);
}
finally
{
_logger.RecordMessage(" ProcessingFiles exiting", Log.MessageType.Info);
}
}
#endregion
public bool ProcessIndividualFile(string strFile, string strWebTISFileDirectory, string strErrorFileDirectory, string strConnectionString)
{
_file = strFile;
//_logFileName = strLogFileName;
_xmlFileDirectory = strWebTISFileDirectory;
_errorFileDirectory = strErrorFileDirectory;
_errorStr = new ArrayList();
_iNoOfRecordsExported = 0;
_connectionString = strConnectionString;
_logger.RecordMessage("", Log.MessageType.Info);
_logger.RecordMessage(" processing " + _file, Log.MessageType.Info);
_logger.RecordMessage("", Log.MessageType.Info);
try
{
//' deserialize the xml file
HouseCouncilTaxDetails cData;
using (System.IO.FileStream fs = new System.IO.FileStream(_file, System.IO.FileMode.Open))
{
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(typeof(HouseCouncilTaxDetails));
cData = (HouseCouncilTaxDetails)xsSerializer.Deserialize(fs);
}
ProcessHouseCouncilTaxDetails(cData);
HandleErrors();
return true;
}
catch (Exception ex)
{
//Util.LogMessage(_logFileName, " exception " + ex.InnerException + ex.StackTrace);
_logger.RecordMessage(ex, Log.MessageType.Info);
return false;
}
}
private void ProcessHouseCouncilTaxDetails(HouseCouncilTaxDetails cSTD)
{
string sSQL = "";
_iNoOfRecordsExported = 0;
_iTotalNoOfRecords = cSTD.HouseCouncilTaxList.Count;
for (int i = 0; i <= _iTotalNoOfRecords - 2; i = i + 2)
{
HouseDetails house = (HouseDetails)cSTD.HouseCouncilTaxList[i];
CouncilTaxDetails councilTax = (CouncilTaxDetails)cSTD.HouseCouncilTaxList[i + 1];
_logger.RecordMessage("", Log.MessageType.Info);
_logger.RecordMessage("House - " + house.HOUSENAME + " ; CouncilTax - " + councilTax.PAYMENTDATE, Log.MessageType.Info);
_logger.RecordMessage("", Log.MessageType.Info);
try
{
sSQL = CreateSQLQuery(house, councilTax);
bool result = UpdateDatabase(sSQL);
if (result)
{
_iNoOfRecordsExported = _iNoOfRecordsExported + 2;
}
else
{
_errorStr.Add("Unable to export. House : " + house.HOUSENAME + " " + house.POSTCODE + "Council Tax : " + councilTax.PAYMENTDATE);
}
}
catch (Exception ex)
{
_errorStr.Add(ex.Message + " House : " + house.HOUSENAME + " " + house.POSTCODE + "(" + councilTax.PAYMENTDATE + " )Council Tax amount : " + councilTax.AMOUNT);
}
}
}
private void HandleErrors()
{
if ((_errorStr != null))
{
if (_errorStr.Count > 0)
{
string fileName = MoveFileToDirectory(_file, _errorFileDirectory, "Unable to upload " + (_iTotalNoOfRecords - _iNoOfRecordsExported) + " records.");
foreach (string str in _errorStr)
{
try
{
AddErrorNode(_errorFileDirectory + "\\" + fileName, str);
}
catch (Exception ex)
{
_logger.RecordMessage(ex, Log.MessageType.Error);
//return false;
}
}
}
else
{
System.IO.File.Delete(_file);
}
}
}
private string CreateSQLQuery(HouseDetails house, CouncilTaxDetails councilTax)
{
string sSQL = "execute UpdateCouncilTax ";
sSQL += "@HouseName='" + house.HOUSENAME + "',@PostCode='" + house.POSTCODE
+ "'" ;
return sSQL;
}
#region "UpdateDatabase - updates the database with the customer and seasons records."
private bool UpdateDatabase(string queryString)
{
_logger.RecordMessage(queryString, Log.MessageType.Info);
using (SqlConnection connection = new SqlConnection(
_connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
int records = 0;
try
{
records = command.ExecuteNonQuery();
}
catch (Exception ex)
{
_logger.RecordMessage(ex, Log.MessageType.Info);
}
if (records > 0)
{
// successful so move them to uploaded directory
//Log("Data export ran successfully. , Logging.LoggingLevel.Info)
//MoveFileToDirectory(sFile, UploadedFilesFolder, "")
//DeleteFile(sFile)
Thread.Sleep(500);
return true;
}
else
{
//Log("Data export failed - Records = " + records.ToString(), Logging.LoggingLevel.Warning);
//sProcessingStatus = "Data export failed - Records = " + records.ToString();
_logger.RecordMessage("4----------------------", Log.MessageType.Info);
return false;
}
}
}
#endregion
#region "MoveFileToErrorsDirectory Procedure"
private string MoveFileToDirectory(string sFile, string sDir, string errorDetails)
{
// move the file passed in to the Errors directory
System.IO.FileInfo fI = null;
try
{
if (Util.CreateDirectory(sDir) == true)
{
fI = new System.IO.FileInfo(sFile);
_logger.RecordMessage("MoveFileToDirectory: " + fI.Name, Log.MessageType.Info);
string fileName = String.Format("{0:yyyy-MM-dd(HH mm ss)}", DateTime.Now) + " " + fI.Name;
System.IO.File.Move(sFile, sDir + "\\" + fileName);
//AddErrorNode(sDir & "\" & fI.Name(), errorDetails)
//sProcessingStatus = "Moved file " & sFile & " to " & sDir & "(" & errorDetails & ")"
return fileName;
}
else
{
return "";
}
}
catch (Exception ex)
{
_logger.RecordMessage(ex, Log.MessageType.Info);
throw ex;
}
}
#endregion
private void AddErrorNode(string sFile, string errorDetails)
{
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
try
{
xmldoc.Load(sFile);
//If Not errorDetails.Equals("") AndAlso xmldoc.SelectSingleNode("Error") Is Nothing Then
if (!errorDetails.Equals(""))
{
System.Xml.XmlNode SectionName = xmldoc.CreateNode(System.Xml.XmlNodeType.Element, "Error", "");
SectionName.InnerText = errorDetails;
xmldoc.SelectSingleNode("/*").AppendChild(SectionName);
}
xmldoc.Save(sFile);
}
catch (Exception ex)
{
_logger.RecordMessage(ex, Log.MessageType.Info);
//cLogging.Log(ex, Logging.LoggingLevel.Exception, "AddErrorNode");
}
}
}
}
样本xml文件
Sample xml file
<HouseCouncilTaxDetails>
<House HOUSENAME="a" POSTCODE="ABCDEF">
</House>
<CouncilTax PAYMENTDATE="SDF" AMOUNT="343">
</CouncilTax>
</HouseCouncilTaxDetails
>
>
推荐答案
HI Visual Studio.Net 2008和2010带有内置的自动单元测试用例生成,并运行测试应用程序以测试搜索
在Viusual studio.Net 2008/2010 IDE中,单击测试"菜单->新测试->选择单元测试->输入测试项目名称
从Google搜索更多信息,以使用Visual Studio.Net 2008/2010进行自动单元测试
HI Visual Studio.Net 2008 and 2010 comes with inbuilt automatic unit testcase generation and run the test application to test search
In Viusual studio.Net 2008/ 2010 IDE click on Test menu --> New Test --> Select Unit Test --> enter test project name
More information search from google for automatic unit testing with Visual Studio.Net 2008/ 2010
这篇关于帮助进行单元测试C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文