Gaurav123
Gaurav123

Reputation: 5209

Pass multiple mock objects to a method

I have a method CreateAccount to test. I am using Moq for the same.

Under CreateAccount method, there are multiple table insertion methods which belongs to two classes AccountRepository and BillingRepository

I have setup the Moq but don't know how to use multiple moq objects.

Below is some code snippet

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 method takes four parameters and its under ApplicationService class

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);
    }
}

Please suggest some solution. How can these three methods will be skipped ?

Thanks in advance.

Upvotes: 0

Views: 2262

Answers (1)

paulroho
paulroho

Reputation: 1266

You have to provide some means to inject obj_1 and obj_2, since they seem to represent your instances of AccountRepository and BillingRepository, resp.

Typically, you might want to do this by using constructor injection. Extending the snippet you provided, this might look like this:

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);
    }
}

Now you can inject your mocks into the class under test:

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
}

Upvotes: 1

Related Questions