我正在为我的数据库连接编写单元测试。
我有以下课程
Public class A
{
public IDbConnection _dbConnection;
public A()
{
_dbConnection = new SqlConnection(connectionStringName);
}
public int ExecuteNoneQuery(CommandDefination command)
{
return _dbConnection.Execute(command);
}
}
我想测试这个类,我可以用Microsoft Stub / Shim测试
我已经编写了以下代码,但它无效。
[TestMethod]
public void TestMethod1()
{
StubIDbConnection stubIDbConnection = new StubIDbConnection();
stubIDbConnection.Execute =(null) => -1;
var a = new classA();
int answer = a.ExecuteNoneQuery(null);
Assert.AreEqual(-1, answer);
}
答案 0 :(得分:0)
您可以轻松地使用A类的构造函数来插入依赖项,将以下构造函数添加到类A中:
public A(IDBConnection connection)
{
_dbConnection = connection;
}
然后你的测试看起来像:
[TestMethod]
public void TestMethod1()
{
StubIDbConnection stubIDbConnection = new StubIDbConnection();
stubIDbConnection.Execute =(null) => -1;
var a = new classA(stubIDbConnection);
int answer = a.ExecuteNoneQuery(null);
Assert.AreEqual(-1,answer);
}