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?
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
Strict the mock behaves just like the object of the class you've mocked. It causes the mock to always throw an exception for invocations that don't have a corresponding expectation. Thus, if the you slightly changed the class (added a method), you'll also want to add that method to the mock to make your tests pass.
Simpler mock objects, using MoqRight-click on the TestEngine project (the one we want to add Moq to). Select “Manage NuGet Packages…” In the NuGet tab, select “Browse” and search for “Moq” – the library we want to add. There are several add-on libraries that make it easier to use Moq in different types of programs.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With