Since you are using Linq for Sql, here is an example of testing the script that you mentioned using NUnit and Moq. I do not know the exact data of your DataContext and what you have in it. Change for your needs.
You will need to wrap the DataContext with a special class, you cannot Mock the DataContext with Moq. You also cannot scoff at SqlException because it is sealed. You will need to wrap it with your own Exception class. It is not difficult to accomplish these two things.
Let's start by creating our test:
[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);
Let me implement the test, first enable our Linq to Sql calls using the repository template:
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); } }
Then create an IDataContextWrapper so that you can view this blog post by topic, mine is a little different:
public interface IDataContextWrapper : IDisposable { Table<T> Table<T>() where T : class; }
Next, create the CustomSqlException class:
public class CustomSqlException : Exception { public CustomSqlException() { } public CustomSqlException(string message, SqlException innerException) : base(message, innerException) { } }
Here is an example implementation of 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) {
Dale Ragan Sep 07 '09 at 6:22 2009-09-07 06:22
source share