Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(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?

like image 985
Frank Michael Kraft Avatar asked Jun 04 '10 16:06

Frank Michael Kraft


People also ask

Can we mock a constructor?

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.

What is Mockbehavior strict?

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.

How do you create a object in MOQ?

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.


2 Answers

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.

like image 116
womp Avatar answered Sep 23 '22 08:09

womp


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.

like image 39
Finglas Avatar answered Sep 20 '22 08:09

Finglas