【发布时间】:2018-02-23 00:34:33
【问题描述】:
我是单元测试的新手。我有这些类 AccountBl 调用 DataStore 使用 SqlConnection 从数据库中获取数据。
我需要通过模拟数据源来测试AccountBl.GetInvestmentAccounts方法,即使没有数据库连接也需要运行测试。
这里是给定的类AccountBl:
public class AccountBl
{
private readonly DataStore dataStore = new DataStore();
public List<Account> GetInvestmentAccounts(int clientId, AccountType accountType)
{
if (accountType == AccountType.Investment)
{
var accounts = dataStore.LoadAccounts(clientId);
return accounts.Where(a => a.AccountType == AccountType.Investment).ToList();
}
throw new Exception("Invalid account type provided");
}
}
和DataStore:
public class DataStore
{
public static string GetAccountsSql = "irrelevant query";
public virtual List<Account> LoadAccounts(int clientId)
{
using (var connection = CreateConnection())
{
var sqlCommand = connection.CreateCommand();
sqlCommand.CommandText = GetAccountsSql;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("@clientId", clientId);
var reader = sqlCommand.ExecuteReader();
var accounts = new List<Account>();
while (reader.Read())
{
var account = new Account();
account.AccountNumber = (string)reader["number"];
account.AccountOwner = clientId;
if (reader["accountType"] == null || reader["accountType"] == DBNull.Value)
{
account.AccountType = AccountType.Checking;
}
else
{
account.AccountType =
(AccountType)Enum.Parse(typeof(AccountType), reader["accountType"].ToString());
}
accounts.Add(account);
}
return accounts;
}
}
private static SqlConnection CreateConnection()
{
var sqlConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
sqlConnection.Open();
return sqlConnection;
}
}
这是我的TestClass
[TestClass]
public class UnitTest1
{
[TestMethod]
public void GetInvestmentAccountsTest()
{
var clientId = 25;
var mockAccounts = new List<Account>
{
new Account{AccountNumber = "aaa", AccountOwner = clientId, AccountType = AccountType.Investment},
new Account{AccountNumber = "bbb", AccountOwner = clientId, AccountType = AccountType.Savings},
new Account{AccountNumber = "ccc", AccountOwner = clientId, AccountType = AccountType.Checking},
};
var mockDatastore = new Mock<DataStore>();
mockDatastore.Setup(x => x.LoadAccounts(clientId)).Returns(mockAccounts);
var accountBl = new AccountBl();
var accounts = accountBl.GetInvestmentAccounts(clientId, AccountType.Investment);
}
}
我运行时收到错误消息
消息:测试方法 ScreeningSample.Tests.UnitTest1.GetInvestmentAccountsTest 抛出 异常:System.InvalidOperationException:ConnectionString 属性尚未初始化。
显然它试图创建一个连接,但我需要在没有连接的情况下运行测试。
我是不是在模拟错误?
【问题讨论】:
标签: c# unit-testing moq mstest