Use Moq to mock Constructor?

前提是你 提交于 2019-12-09 14:04:21

问题


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?


回答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.




回答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.




回答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.



来源:https://stackoverflow.com/questions/2976018/use-moq-to-mock-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!