Use Moq to mock Constructor?
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(dataCon开发者_开发百科nectionString).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?
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.
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.
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.
Use factory and remove the two first constructors. Access CloudStorageAccount
from the factory. Even better, hide CloudStorageAccount
behind an interface because now it seems like you are using static methods.
精彩评论