Use Moq to mock Constructor?

42,628

Solution 1

It sounds as if you have a code smell - the constructor is doing too much work. The article includes a set of fixes for such scenarios. Basically the answer is to only perform assignment in constructors, not execute business logic.

Solution 2

var myMockBOC = new Mock<BusinessObjectContext>(null, null);

This will pass nulls in for your two parameters.

Another approach would be to create an internal constructor meant for test usage only, and use InternalsVisibleTo to allow your test assembly to use it. Unfortunately this has a big drawback in that if you sign your assemblies, Moq is unable to use the constructor. This is supposed to be addressed in the 4.0 release of Moq though.

Solution 3

If you don't want to use your constructor parameters you might pass with It.IsAny() method while you mocking it. It would pass null value to it. It would be much more readable when you use this method instead of writing null.

Share:
42,628
Frank Michael Kraft
Author by

Frank Michael Kraft

Updated on July 25, 2020

Comments

  • Frank Michael Kraft
    Frank Michael Kraft almost 4 years

    I have such a set of Constructors:

    public BusinessObjectContext()
             : this(CloudStorageAccount.FromConfigurationSetting("DataConnectionString").TableEndpoint.ToString(),
                    CloudStorageAccount.FromConfigurationSetting("DataConnectionString").Credentials) {}
    
    public BusinessObjectContext(string dataConnectionString)
             : this(CloudStorageAccount.Parse(dataConnectionString).TableEndpoint.ToString(),
                    CloudStorageAccount.Parse(dataConnectionString).Credentials) { }
    
    public BusinessObjectContext(String baseAddress, StorageCredentials credentials) 
             : base(baseAddress, credentials) { } 
    

    However when testing / Mocking I need the object without any of the connection string parameters. How can I do this - preferrably in Moq?

    Is this possible at all?