我目前正在尝试使用Moq学习Mocking,我想在我拥有的现有数据库上尝试它,但我不确定如何正确处理这个问题。
在我的数据层中,我有一个处理连接到数据库的类,并且有各种插入,选择等方法。我想测试一个actor是否正确插入到数据库中。
我的插入方法目前看起来像这样:
public void Insert(string firstname, string lastname)
{
string query = $"INSERT INTO `sakila`.`actor`(`first_name`,`last_name`) VALUES('" + firstname + "','" + lastname + "')";
Console.WriteLine(query);
//open connection
if (this.OpenConnection() == true)
{
Console.WriteLine("Established connection");
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
Console.WriteLine("Insert query succesfully executed.");
//close connection
this.CloseConnection();
}
}
我如何使用Mocks进行此操作?我是否为actor实体创建了一个类?我应该为DbConnection
课程创建一个界面吗?
对不起所有的问题,但我真的很难解决如何解决这个问题。
答案 0 :(得分:3)
目前正在测试的方法与实现问题紧密耦合,使其易于单独测试。尝试将这些实现问题抽象出来,以便可以轻松地模拟它们进行隔离测试。
public interface IDbConnectionFactory {
IDbConnection CreateConnection();
}
上述连接工厂抽象可用于访问MySql数据存储的其他必要System.Data
抽象。
public class MyDataAccessClass {
private IDbConnectionFactory connectionFactory;
public MyDataAccessClass(IDbConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void Insert(string firstname, string lastname) {
var query = $"INSERT INTO `sakila`.`actor`(`first_name`,`last_name`) VALUES('" + firstname + "','" + lastname + "')";
Console.WriteLine(query);
using(var connection = connectionFactory.CreateConnection() {
//Creates and returns a MySqlCommand object associated with the MySqlConnection.
using(var command = connection.CreateCommand()) {
command.CommandText = query;
Console.WriteLine("Established connection");
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("Insert query succesfully executed.");
connection.Close();//is not actually necessary as the using statement will make sure to close the connection.
}
}
}
}
工厂的生产实施将返回实际的MySqlConnection
public class MySqlConnectionFactory: IDbConnectionFactory {
public IDbConnection CreateConnection() {
return new MySqlConnection("connection string");
}
}
可以通过依赖注入传递到数据层
对于测试,您可以使用您选择的模拟框架模拟接口,或创建自己的假货来注入和测试您的方法。
[TestClass]
public class DataAccessLayerUnitTest {
[TestMethod]
public void TestInsert() {
//Arrange
var commandMock = new Mock<IDbCommand>();
commandMock
.Setup(m => m.ExecuteNonQuery())
.Verifiable();
var connectionMock = new Mock<IDbConnection>();
connectionMock
.Setup(m => m.CreateCommand())
.Returns(commandMock.Object);
var connectionFactoryMock = new Mock<IDbConnectionFactory>();
connectionFactoryMock
.Setup(m => m.CreateConnection())
.Returns(connectionMock.Object);
var sut = new MyDataAccessClass(connectionFactoryMock.Object);
var firstName = "John";
var lastName = "Doe";
//Act
sut.Insert(firstName, lastName);
//Assert
commandMock.Verify();
}
}
最后建议您在命令文本中使用命令参数,因为构建查询字符串会手动打开代码,直到SQL注入攻击。
为了更好地了解如何使用Moq检查他们的Quickstart