I'm writing unit tests for one of our products and have been used Moq to successfully mock connections to Entity Framework. However, I've come across the following method:
public static productValue findValues(string productName, string dbConnectionString)
{
try
{
SqlConnection conn = new SqlConnection(dbConnectionString);
conn.Open();
//Do stuff
}
}
Which accesses our database inside that method using a passed connection string. Is it possible to setup a mock DB using Moq and create a connection string which points to the mocked DB? I've trying doing something along the lines of
var mockSqlConnnection = new Mock<SqlConnection>();
Though I'm unsure if this is the correct approach, as this would mock the connection itself rather than the DB.
I had a similar problem.
I introduced an
SqlDataContext
wrapper around the SqlConnection which inherited from andISqlDataContext
interface:You can add overloads to the ISqlDataContext as you need.
What this means is that you can then mock the ISqlDataContext as requires using Moq or similar and return mock values.
Means you can then test your repository or anything else that hits the database through the SqlConnection without actually having to hit the database.
The other advantage is that you can inject ISqlContext with DI / IoC as needed.
Have a look at the Repository Pattern, essentially you would mock the data in your consuming classes, rather than worrying about the implementation of talking to the database.
Essentially, you would have a repository
Which is then consumed in other classes:
And used as:
The full example is in the link at the top.
So then you would pass a mocked repository into your class:
late but why not with mstest:
you need to add a reference to System.Data and then add a Fake for it.
https://msdn.microsoft.com/en-us/library/hh549175.aspx Better is it, if you change the implementation and you can change the used read layer but ...