在 MVC 中对控制器进行 MOQing

MOQing a controller in MVC

我有以下控制器

 public class ProviderController : Controller
{
    private static readonly IProviderRepository _repository = new ProviderRepository();
    private static readonly Ilogger Logger = new Logger();     

    [HttpPost]
    public ActionResult CreateProvider(Provider provider)
    {
        try
        {
            int providerCreationSuccessful = _repository.CreateProvider(provider);
            if (providerCreationSuccessful == 1)
                TempData["userIntimation"] = "Provider Registered Successfully";

            return RedirectToAction("ShowTheListOfProviders");
        }
        catch (Exception Ex)
        {
            Logger.Error(Ex.Message);
            return View("Error");
        }
    }
 }

IProviderRepository 看起来像这样。

public interface IProviderRepository
{
    List<Provider> GetListofProviders();

    Provider GetSingleProviderDetails(int ProviderID);

    int CreateProvider(Provider provider);

    int DeleteProvider(int ProviderID);

    int UpdateProviderDetails(Provider provider);
}

我必须对控制器进行 MOQ apparently.I 我猜这意味着我必须对 methods.So 进行 MPOQ,我使用以下方法创建了一个测试项目。

 public class ProviderControllerTests
{
    Provider _provider;
    Mock<IProviderRepository> mockProviderRepository;

    [TestInitialize]
    public void InitializeTestData()
    {
        _provider = new Provider();
        mockProviderRepository = new Mock<IProviderRepository>();
    }
  [TestMethod()]
    public void repository_CreateProviderTest()
    {
        //Act
        mockProviderRepository.Setup(provider => provider.CreateProvider(_provider)).Returns(1);
        //Assert
        throw new NotImplementedException();
    }
}

有人可以指导我到底需要模拟什么吗here.I感觉我有点不知所措。

您需要模拟您已经完成的 IProviderRepository。

mockProviderRepository = new Mock<IProviderRepository>();

为了不与真实数据库交互,您必须执行以下操作

[TestInitialize]
    public void InitializeTestData()
    {
        _provider = new Provider();
        mockProviderRepository = new Mock<IProviderRepository>();
        _provider._repository=mockProviderRepository.Object;

    }

因此,您现在可以使用此模拟存储库测试 ProviderController 的操作。

[TestMethod()]
    public void repository_CreateProviderTest()
    {
        //Act
        mockProviderRepository.Setup(provider => provider.CreateProvider(_provider)).Returns(1);
        Provider provider = new Provider() {//with data};
       _provider.CreateProvider(Provider provider);
       //Your Assertion

}