如何在MOQ中使用new关键字模拟在方法内部创建的类对象

时间:2019-01-11 07:24:04

标签: c# moq rhino-mocks testcase

我正在使用Moq编写单元测试用例。

代码:

public class SavingAccount  
{  
    public void Data()  
    {  
        //Some logic
    }  
}  

public class Account  
{  
    public void GetAccountDetails()  
    {  
        SavingAccount savingAccount = new SavingAccount();  
        savingAccount.Data();  

        //Some logic
    }  
}

测试用例:

[TestClass]
public class AccountTest
{
    [TestMethod]
    public void TestGetAccountDetails()
    {
       using(var mock = new AutoMock.GetLoose())
       {
          var mockAccount = mock.Create<Account>();
          mockAccount.GetAccountDetails();
       }
    }
}

在这里,我需要模拟savingAccount.Data();类的SavingAccount方法。 但是,当我运行上述测试时,savingAccount个对象实际上调用了Data()方法。我不想称呼它,只是想嘲笑它。

我也不更改上面的代码。我不想使用该界面。

1 个答案:

答案 0 :(得分:1)

我可以想到两种方式:

方法1。。创建工厂并将其实例化时传递给Account。当您需要一个SavingAccount时,请致电工厂:

    public class Account
    {
        private readonly IAccountFactory _accountFactory;

        public Account(IAccountFactory accountFactory)
        {
            _accountFactory = accountFactory;
        }

        public void GetAccountDetails()  
        {  
            SavingAccount savingAccount = _accountFactory.CreateSavingAccount();
            savingAccount.Data();  

            //Some logic
        }   
    }

然后,您可以将IAccountFactory的模拟实现传递到Account中。这是我建议的方式,如果您决定这样做,将来可以更轻松地过渡到依赖项注入。

方法2。将SavingAccount的实例化为可模拟的方法:

    public class Account  
    {  
        public void GetAccountDetails()  
        {  
            SavingAccount savingAccount = CreateSavingAccount();
            savingAccount.Data();  

            //Some logic
        }

        protected virtual SavingAccount CreateSavingAccount()
        {
            return new SavingAccount();
        }
    }

现在,您可以模拟CreateSavingAccount,并使其返回SavingAccount的模拟实例。请注意,您还需要将public void Data()更改为public virtual void Data(),以便对其进行模拟。