0

I am trying to mock the below method,

public static object ExecuteGetObj(string query)
{
    object obj = null;

    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
    {
        connection.Open();

        using (SqlCommand cmd = new SqlCommand(query, connection))
        {
            obj = cmd.ExecuteScalar();
        }
    }

    return obj;
}

but it is not using the Mock SqlConnection instead it is trying to create the SqlConnection

 var command = new Mock<IDbCommand>();
 command.Setup(x => x.ExecuteScalar())
            .Verifiable();

 var connection = new Mock<IDbConnection>();
 connection
        .Setup(m => m.CreateCommand())
            .Returns(command.Object);

 connection.Object.Open();


 var obj = Common.ExecuteGetObj(sql);

 Assert.IsNull(obj);
ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
Hary
  • 5,690
  • 7
  • 42
  • 79

1 Answers1

3

You can only mock either abstract classes or interfaces, so this is not going to work.

This code instantiates a SqlConnection, nowhere does it use the Mock<IDbConnection> you setup in the test. If you absolutely do want to unit test this code, the code itself needs to change; it needs to be passed a IDbConnection somehow, whether as a constructor argument (you need to have a non static class) or as an argument to the method itself, which you then can mock.

I would recommend against unit testing this method though, what problem are you trying to solve? It is generally considered bad practice to change code just to be able to test it. If you want to test this, you could look into integrating testing; if this code is part of an API you could (for instance) do end to end testing on that level.

Aage
  • 5,932
  • 2
  • 32
  • 57