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
I am trying to mock out the constructor of a class.

Mock<DocumentManager> mockDManager = MockManager.Mock<DocumentManager>(Constructor.Mocked);

When running my test it gets to a line in a function:

public string GenerateFileName(string fileName, string extension, string userId, DataConnection dbConn)

       DocumentManager docManager = new DocumentManager(dbConn.ActiveConnection, dbConn.CreateAdapter());

       return (docManager.CreateWorkingDocument(fileName, extension, userId));

Fails at the first line, with: System.NullReferenceException: Object reference not set to an instance of an object..

I don't want it to create a new instance of the DocumentManager based on the DataConnection instance (a SQL database connection class), I want it to just create a mocked object and continue on and call the 2nd line, the CreateWorkingDocument function which doesn't really need the database connection. Stepping through the code it actually goes through and looks up the dbConn.ActiveConnection and calls dbConn.CreateAdapter().

How do I set it up to do what I am expecting it to do?
asked by repairman2003 (1.7k points)

1 Answer

0 votes
If I'm reading you correctly, the problem is that before the mocked DocumentManager ctor is called, it evaluates the parameters sent to it, i.e. calls the dbConn.ActiveConnection and dbConn.CreateAdapter.
I'm guessing that the dbConn Object is not initialized causing the null reference exception.

I would approach the problem by mocking the calls made on dbConn.
specifically mocking the calls to ActiveConnection and CreateAdapter.

:idea: Sometimes to understand what exactly need to be done it helps to split the code so each line contains a single method call. For example, look at the following segment (which is equivalent to the problematic line):

object activeConnection = dbConn.ActiveConnection;
object adapter dbConn.CreateAdapter();
DocumentManager docManager = new DocumentManager(activeConnection,CreateAdapter);

:!: Keep in mind that if you mock the call to the constructor, it wont be initialized properly so if any following calls depends on members being initialized might fail. (if this is your case you might want to think about calling the real constructor and only mocking usage of the database connection.
answered by lior (13.2k points)