I have followed Mocking insert query to a MySQL Database using Moq as a guideline to do moq. In my case, I will do moq with postgesql.
Test case is passed. However, I have a question: why "Update query successfully executed" is shown while postgresql's connection state is closed? Is it as expected result when we do moq? If it's not expected result, what should I do?
Thanks in advance.
Here is Console's result After running this test.
UPDATE DEVICES SET user_id=null WHERE camera_id = 'G41140'
Established connection
State Before open : Closed
State After open : Closed
Update query succesfully executed.
This is a part of my code
[Test, Order(1)]
public void UpdateTest()
{
//Arrange
DumpDatabase databaseSetting = new DumpDatabase();
//Assume, fill the right setting for db
databaseSetting.Host = "***.***.*.**";
databaseSetting.Port = "****";
databaseSetting.Database = "*****";
databaseSetting.UserName = "******";
databaseSetting.Password = "***********";
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 DumpConnection(connectionFactoryMock.Object, databaseSetting);
// Act
sut.Update();
// Assert
commandMock.Verify();
}
public class DumpConnection : IDbConnectionFactory
{
DumpDatabase _databaseSetting;
private IDbConnectionFactory connectionFactory;
public DumpConnection(IDbConnectionFactory connectionFactory, DumpDatabase databaseSetting)
{
this.connectionFactory = connectionFactory;
this._databaseSetting = databaseSetting;
}
public IDbConnection CreateConnection()
{
return new NpgsqlConnection("Server=" + _databaseSetting.Host + ";User Id=" + _databaseSetting.UserName + "; " +
"Password=" + _databaseSetting.Password + ";Database=" + _databaseSetting.Database + ";");
}
public void Update()
{
string query = "UPDATE DEVICES SET user_id=null WHERE camera_id = 'G41140' ";
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");
Console.WriteLine("State Before open : " + connection.State);
connection.Open();
Console.WriteLine("State After open : " + connection.State);
Console.WriteLine("Update query succesfully executed.");
}
}
}
}
public interface IDbConnectionFactory
{
IDbConnection CreateConnection();
}