chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Could you give some sample code on mocking a SQLConnection object and then checking valid connection string, invalid connection etc
asked by robpearmain (2.8k points)

4 Answers

0 votes
It depends how your code is written here is a small example.
You should read the documentation about how to set up expectations:
(Taken from another post)
// mock the next sqlConnection instance
m_MockConnection = MockManager.Mock(typeof(SqlConnection));

// expect a certain connection string (you can use Custom Parameter
// checkers to do a dynamic check)
m_MockConnection.ExpectConstructor().Args("your connection string");

// mock Open, you can mock throwing an exception by using
// ExpectAndThrow("Open",new SqlException())

// Mock State and return Open
// Mock the next sqlCommand instance
MockObject mockCommand = MockManager.Mock(typeof(SqlCommand));
// Create the mocked instancem, you can add expectations
SqlCommand command = new SqlCommand();

// return it when Connection.CreateCommand is called
answered by scott (32k points)
0 votes
Many thanks, excellent, it all makes sense now
answered by robpearmain (2.8k points)
0 votes
I have been trying this and I think there is a problem with the examples you are showing.
ExpectAndThrow("Open",new SqlException()) 

This fails to compile because the constructor for SqlException is private. Is there any other way to mock the connection and test for an SqlException being thrown?
answered by echmyr (2.2k points)
0 votes
Never mind, I figured it out :wink: . It takes a bit of Reflection magic to accomplish thought.

         Mock mockConn = MockManager.Mock(typeof(SqlConnection));
         Type typeEx = typeof(SqlException);
         ConstructorInfo[] info = typeEx.GetConstructors(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance );
         Object obj = info[0].Invoke(null);
         mockConn.ExpectAndThrow("Open", (SqlException)obj);

The BindingFlags are needed to get the non-public constructors for the object.
answered by echmyr (2.2k points)