c#-使用Moq模拟对MySQL数据库的插入查询
作者:互联网
我目前正在尝试学习使用Moq进行模拟,并且想在现有的数据库中进行尝试,但是我不确定如何正确地实现这一目标.
在我的数据层中,我有一个处理连接到DB的类,并具有用于插入,选择等的各种方法.我想测试一个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做到这一点?我是否为演员实体创建一个类?我应该为我的DbConnection类创建一个接口吗?
对不起所有问题,但是我真的对如何解决这个问题感到困惑.
解决方法:
当前,被测方法过于紧密地与实现问题联系在一起,以致于无法轻松地对其进行单独的单元测试.尝试抽象出这些实现问题,以便可以轻松模拟它们以进行独立测试.
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
标签:unit-testing,mocking,moq,c,mysql 来源: https://codeday.me/bug/20191111/2021037.html