MOQing MVC中的控制器

时间:2015-02-12 10:39:45

标签: asp.net-mvc repository moq-3

我有以下控制器

 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控制器。我猜这意味着我对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();
    }
}

有人可以指导我在这里嘲笑我究竟需要什么。我觉得我有点过头了。

1 个答案:

答案 0 :(得分:1)

您需要模拟已完成的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

}