【问题标题】:How can I mock up a repository method that is being used inside the Method to test (in the model)如何模拟在方法内部用于测试的存储库方法(在模型中)
【发布时间】:2013-07-11 14:48:15
【问题描述】:

我正在尝试让这个用例为我工作:

我有一个存储库类:ABCRepository 它有一个虚拟方法GetMyValues()

一个模型类:ABCModel,有一个方法ABCToTest()。 在这个ABCToTest() 中,我正在尝试使用Ninject 访问ABCRepository:

  var repo =  kernel.Get<ABCRepository>();

    //further using repository method

    var results =  repo.GetMyValues();

现在,我正在使用以下代码为 ABCToTest() 创建 Unittest 并模拟 GetMyValues() 方法:

            var kernel = new MoqMockingKernel();

            kernel.Bind<ABCRepository>().ToMock();


            kernel.Bind<ABCModel>().ToMock();

            var abcRepo= kernel.GetMock<ABCRepository>();



            abcRepo.Setup(repo => repo.GetMyValues()).Returns("ABC");

//This is a static method I am using to initialize the kernel object, ABCToTest() method is using.
            MvcApplication.InitializeInjection(kernel);

            var model= kernel.GetMock<ABCModel>().Object;

            model.ABCToTest("177737");

当我尝试调试/运行测试时,我可以看到,ABCTotTest 内部的GetMyValues() 方法调用没有返回“ABC”,而是返回NULL。

我对这个实现有什么问题?任何建议和指针都非常感谢..

感谢和问候 苏梅特

【问题讨论】:

    标签: c# asp.net-mvc-4 ninject moq xunit


    【解决方案1】:

    您似乎偶然发现了服务定位器反模式 (http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/)

    您应该更改 ABCModel 类,以便将 ABCRepository 注入构造函数:

    private readonly IABCRepository repo;
    
    public ABCModel(IABCRepository repo)
    {
        this.repo = repo;
    }
    

    那么您的单元测试将如下所示:

    private Mock<IABCRepository> mockRepo;
    private ABCModel model;
    
    [SetUp]
    public void SetUp()
    {
        mockRepo = new Mock<IABCRepository>();
    
        model = new ABCModel(mockRepo.Object);
    }    
    
    [Test]
    public void ABCToTest_WhenCalled_CallsRepository
    {       
        model.ABCToTest("177737");
    
        mockRepo.Verify(a => a.GetMyValues(), Times.Once);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 2019-07-07
      • 2021-02-13
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      相关资源
      最近更新 更多