【发布时间】:2015-11-02 15:44:32
【问题描述】:
我是单元测试的新手,所以我一直在尝试编写一些示例来学习使用它们的正确方法。我有一个使用实体框架连接到数据库的示例项目。
我正在使用由一个使用 EF 查询数据库的数据访问层、一个调用数据访问层方法来查询数据库并使用检索到的数据执行其业务目的的业务层和一个服务层组成的 n 层架构它由简单地调用业务层对象的 WCF 服务组成。
我是否必须为每一层(数据访问、业务层、服务层)编写单元测试代码?
为查询数据库的方法编写单元测试的正确方法是什么?下一个代码是我的数据访问层中对数据库执行选择的方法的示例,它的单元测试应该如何?
public class DLEmployee
{
private string _strErrorMessage = string.Empty;
private bool _blnResult = true;
public string strErrorMessage
{
get
{
return _strErrorMessage;
}
}
public bool blnResult
{
get
{
return _blnResult;
}
}
public Employee GetEmployee(int pintId)
{
Employee employee = null;
_blnResult = true;
_strErrorMessage = string.Empty;
try
{
using (var context = new AdventureWorks2012Entities())
{
employee = context.Employees.Where(e => e.BusinessEntityID == pintId).FirstOrDefault();
}
}
catch (Exception ex)
{
_strErrorMessage = ex.Message;
_blnResult = false;
}
return employee;
}
【问题讨论】:
-
您将从模拟框架开始选择权衡取舍。其他人将设置以某种方式恢复的测试数据库或使用在拆除时回滚的事务。见这里stackoverflow.com/questions/22690877/…
-
感谢您的链接,带我去看了单元测试时模拟实体框架的精彩教程asp.net/web-api/overview/testing-and-debugging/…
标签: c# entity-framework wcf unit-testing