【问题标题】:Mock extension methods as an interface [closed]模拟扩展方法作为接口[关闭]
【发布时间】:2012-10-06 15:05:18
【问题描述】:

它已经对其进行了研究,并发现了几个有趣的链接like this但对于我的问题,他们没有帮助我。

代码

我有如下界面

public interface IViewFolderReference
{
    string FolderName { get; set; }
}

扩展

public static ICollection<TFile> GetFiles<TFile>(this IViewFolderReference view)
    where TFile: class, IFile
{
    var folder = view.GetFolder();
    return folder.Exists ? 
        Mapper.Map<ICollection<TFile>>(folder.GetFiles())
        : null;
}

具体类

public class ProcessoViewModel : IViewFolderReference
{
    public string FolderName { get; set; }
    public ICollection<File> Arquivos { get; set; }    
    ...
}

测试方法

[TestMethod]
public void Ao_salvar_processo_adicionar_dois_itens()
{
    // Arrange
    var vm = new Mock<ProcessoViewModel>();
    vm.Object.Arquivos = new List<File>() {
        new File { FileName = "Arquivo 1.jpg", DisplayName = "Arquivo 1" }
        ,new File { FileName = "Arquivo 2.doc", DisplayName = "Arquivo 2" }
    };

    //Act
    controller.salvar(vm.Object); // Problem here!! (GetFiles is called, How can mock the result??)

    //Assert
    var processoDb = repositorio.Query<Processo>().SingleOrDefault(p => p.Imovel == vm.Object.Imovel && vm.Object.DataEntrada == p.DataEntrada);
    Assert.IsNotNull(processoDb.Arquivos);
    Assert.AreEqual(processoDb.Arquivos.Count, 2);
}

【问题讨论】:

  • 查看测试方法->> //这里有问题!! (调用GetFiles,如何mock结果??)

标签: c# unit-testing tdd moq mstest


【解决方案1】:

如果您使用的是 VS 2010,则可以使用 Moles 模拟扩展方法(因为它们只是使用 this 的第一个参数的静态方法)。一个例子here。在 VS 2012 中,你可以使用Microsoft Fakes

【讨论】:

  • 我不知道鼹鼠,我会研究它。与起订量目标相同?
  • 不完全是。 Moq 旨在用作为虚拟/抽象方法设置模拟的简单方法。 Moles 更进一步,允许您模拟静态类、方法和其他一些很酷的东西。
  • Microsoft Fakes 仅在 VS2012 Ultimate 上可用...但感谢它的解决方案。
【解决方案2】:

看起来你真正需要模拟的是view.GetFolder(),它有一个合适的接口可以让你模拟folder.GetFiles()。这样扩展方法 GetFiles 被执行,但最终被底层接口实现模拟。这与模拟应该如何工作是一致的。如果您已经对 GetFiles 扩展方法进行了测试,那么在测试其他内容时调用它并没有什么坏处。

【讨论】:

  • GetFolder 方法访问ConfigurationManager.AppSettings[keyAppConfig + "Folder"] 并使用DirectoryInfo 类创建目录。 我希望它没有。 尝试在方法 GetFolder 中访问 web.config (ConfigurationManager.AppSettings[keyAppConfig + "Folder"]) 时出错
猜你喜欢
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
相关资源
最近更新 更多