使用Moq模拟构造函数? [英] Use Moq to mock Constructor?

查看:427
本文介绍了使用Moq模拟构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一组构造函数:

  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然而,当测试/ Mocking时,我需要的对象没有,但是我不需要这个对象。任何连接字符串参数。

解决方案

这是否可以在Moq中执行?



听起来好像你有代码气味 - 构造函数正在做太多的工作。本文包括一组针对此类场景的修订。基本上,答案是在构造函数中执行赋值,而不是执行业务逻辑。


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?

解决方案

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.

这篇关于使用Moq模拟构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆