单元测试之初试

发表于:2016-8-11 11:17

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:黑色九头鸟    来源:51Testing软件测试网原创

  研究了一周的单元测试,现在勉强算是摸到了门槛,现整理笔记如下:
  项目架构是简单的工厂模式,对应代码为:
  DAL
using System.Collections.Generic;
using MetalsExchange.IDAL;
using MetalsExchange.DBUtility;
using MetalsExchange.Model;
namespace MetalsExchange.SQLServerDAL
{
public class Employee: IEmployee
{
public IList<CustomerInfo> GetCustomerList()
{
IList<CustomerInfo> list = new List<CustomerInfo>();
return list;
}
}
}
  IDAL
using System.Collections.Generic;
using MetalsExchange.Model;
namespace MetalsExchange.IDAL
{
public interface IEmployee
{
IList<CustomerInfo> GetCustomerList();
}
}
  BLL
using System.Collections.Generic;
using MetalsExchange.Model;
using MetalsExchange.IDAL;
namespace MetalsExchange.Bll
{
public  class EmployeeBll
{
public IEmployee dal = DALFactory.DataAccess.CreateEmployee();
public IList<CustomerInfo> GetCustomerList()
{
return dal.GetCustomerList();
}
}
}
  DALFactory
using System.Configuration;
using System.Reflection;
namespace MetalsExchange.DALFactory
{
public class DataAccess
{
private static  string path {
get {
string _path= ConfigurationManager.AppSettings["WebDAL"];
if (_path == null)
_path = "MetalsExchange.SQLServerDAL";
return _path;
}
}
public static IDAL.IEmployee CreateEmployee()
{
string className = path + ".Employee";
return (IDAL.IEmployee)Assembly.Load(path).CreateInstance(className);
}
}
}
  最开始就卡在这里,一度以为静态方法无法单元测试,后来发现原因是因为ConfigurationManager.AppSettings["WebDAL"]取不到值,因为测试项目里面没有config文档,目前我采用了最简单的方法来解决,最好的方法是将这个方法重新封装
  单元测试
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Moq;
using MetalsExchange.IDAL;
using MetalsExchange.Model;
namespace MetalsExchange.Bll.Tests
{
[TestClass()]
public class EmployeeBllTests
{
[TestMethod()]
public void GetCustomerListTest()
{
//arrange
var mock = new Mock<IEmployee>();
mock.Setup(customer => customer.GetCustomerList()).Returns(new List<CustomerInfo>());
EmployeeBll employee = new EmployeeBll();
//art
IList<CustomerInfo> list = employee.GetCustomerList();
mock.Verify();
//assert
Assert.ReferenceEquals(list, mock.Object.GetCustomerList());
}
}
}
  工厂类是一个静态类,其实也可以做单元测试
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MetalsExchange.IDAL;
namespace MetalsExchange.DALFactory.Tests
{
[TestClass()]
public class DataAccessTests
{
[TestMethod()]
public void CreateEmployeeTest()
{
IEmployee dal = DataAccess.CreateEmployee();
Assert.IsNotNull(dal);
}
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号