将多个模拟对象传递给方法

时间:2014-06-18 05:24:26

标签: c# unit-testing mocking moq

我有一个方法 CreateAccount 来测试。我正在使用 Moq

在CreateAccount方法下,有多个表插入方法属于两个类AccountRepository and BillingRepository

我已经设置了Moq但不知道如何使用多个moq对象。

以下是一些代码段

Mock<AccountRepository> moq = new Mock<AccountRepository>();
Mock<BillingRepository> moqBill = new Mock<BillingRepository>();
moq.Setup(x => x.AddTable_1(new AddTable_1 { }));
moq.Setup(x => x.AddTable_2(new AddTable_2 { }));
moqBill.Setup(x => x.Table_3());

CreateAccount 方法需要四个参数及其在 ApplicationService

下的参数
public class ApplicationService
{
public CreateAccountServiceResponse CreateAccount(AuthenticateApp App, CustomerInfo Customer, ServiceInfo Service, Optional op)
    {
       // SOME VALIDATION CODE   
       //.....................



       // SOME CODE TO SAVE DATA INTO TABLES
       obj_1.AddTable_1(objdata_1);
       obj_1.AddTable_2(objdata_2);
       obj_2.AddTable_3(objdata_3);
    }
}

请提出一些解决方案。如何跳过这三种方法?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您必须提供一些方法来注入obj_1obj_2,因为它们似乎代表了AccountRepositoryBillingRepository的实例,分别是

通常,您可能希望使用构造函数注入来执行此操作。扩展您提供的代码段,可能如下所示:

public class ApplicationService
{
    private readonly AccountRepository _accountRepository;
    private readonly BillingRepository _billingRepository;

    public ApplicationService(AccountRepository accountRepository, BillingRepository billingRepository)
    {
        _accountRepository = accountRepository;
        _billingRepository = billingRepository;
    }

    public CreateAccountServiceResponse CreateAccount(AuthenticateApp App, CustomerInfo Customer, ServiceInfo Service, Optional op)
    {
       // SOME VALIDATION CODE   
       //.....................



       // SOME CODE TO SAVE DATA INTO TABLES
       _accountRepository.AddTable_1(objdata_1);
       _accountRepository.AddTable_2(objdata_2);
       _billingRepository.AddTable_3(objdata_3);
    }
}

现在你可以将你的模拟注入被测试的类中:

public void CreateAccount_WhenCalledLikeThis_DoesSomeCoolStuff()
{
     var accountRepoMock = new Mock<AccountRepository>();
     // set it up
     var billingRepository = new Mock<BillingRepository>();
     // set it up
     var appService = new ApplicationService(accountRepoMock.Object, billingRepoMock.Objcet);

     // More setup

     // Act
     var response = appService.CreateAccount(...);

     // Assert on response and/or verify mocks
}