0

我有以下控制器

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

我显然必须对控制器进行最小起订量。我猜这意味着我必须对方法进行 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();
    }
}

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

4

1 回答 1

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

} 
于 2015-02-12T10:58:00.637 回答