由于您正在使用Linq to Sql,这里提供了一个使用NUnit和Moq测试您提到的场景的示例。我不知道您的DataContext的确切细节以及可用内容。请根据您的需求进行编辑。
您需要使用自定义类包装DataContext,无法使用Moq模拟DataContext。由于SqlException是密封的,因此也无法模拟它。您需要使用自己的异常类来包装它。完成这两件事情并不困难。
让我们从创建测试开始:
[Test]
public void FindBy_When_something_goes_wrong_Should_handle_the_CustomSqlException()
{
var mockDataContextWrapper = new Mock<IDataContextWrapper>();
mockDataContextWrapper.Setup(x => x.Table<User>()).Throws<CustomSqlException>();
IUserResository userRespoistory = new UserRepository(mockDataContextWrapper.Object);
User user = userRepository.FindBy(1);
}
让我们来实现测试,首先使用仓储模式封装Linq to Sql调用:
public interface IUserRepository
{
User FindBy(int id);
}
public class UserRepository : IUserRepository
{
public IDataContextWrapper DataContextWrapper { get; protected set; }
public UserRepository(IDataContextWrapper dataContextWrapper)
{
DataContextWrapper = dataContextWrapper;
}
public User FindBy(int id)
{
return DataContextWrapper.Table<User>().SingleOrDefault(u => u.UserID == id);
}
}
接下来,创建IDataContextWrapper,如下所示。您可以在这个博客文章中查看有关此主题的信息。我的略有不同:
public interface IDataContextWrapper : IDisposable
{
Table<T> Table<T>() where T : class;
}
接下来创建CustomSqlException类:
public class CustomSqlException : Exception
{
public CustomSqlException()
{
}
public CustomSqlException(string message, SqlException innerException) : base(message, innerException)
{
}
}
这是一个IDataContextWrapper的样例实现:
public class DataContextWrapper<T> : IDataContextWrapper where T : DataContext, new()
{
private readonly T _db;
public DataContextWrapper()
{
var t = typeof(T);
_db = (T)Activator.CreateInstance(t);
}
public DataContextWrapper(string connectionString)
{
var t = typeof(T);
_db = (T)Activator.CreateInstance(t, connectionString);
}
public Table<TableName> Table<TableName>() where TableName : class
{
try
{
return (Table<TableName>) _db.GetTable(typeof (TableName));
}
catch (SqlException exception)
{
throw new CustomSqlException("Ooops...", exception);
}
}
}