-1

Its already researched about it and found several interesting links like this. But to my problem, they have not helped me.

Code

I have the following interface

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

Extension

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

Concret class

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

Test method

[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);
}
Community
  • 1
  • 1
ridermansb
  • 10,779
  • 24
  • 115
  • 226

2 Answers2

2

If you are using VS 2010, you can use Moles to mock extension methods (as they are simply static methods with the first parameter using this). One example here. In VS 2012, you can use Microsoft Fakes.

Damian Schenkelman
  • 3,505
  • 1
  • 15
  • 19
0

It looks like what you really need to mock is view.GetFolder() with a suitable interface that lets you mock folder.GetFiles(). This way the extension method GetFiles gets executed, but is ultimately mocked by the underlying interface implementation. This is in line with how the mocking should be working. If you already have a test for the GetFiles extension method, there is no harm in calling it during a test for something else.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • The `GetFolder` method access `ConfigurationManager.AppSettings[keyAppConfig + "Folder"]` and creates directory using the `DirectoryInfo` class. **I wish it did not.** An error occurs when trying to access the web.config (`ConfigurationManager.AppSettings[keyAppConfig + "Folder"]`) in method `GetFolder` – ridermansb Oct 06 '12 at 16:16