1

I have used this DistinctBy method with that difference that i'm not using it as an extension. Now i want to write an unit test for another method that is calling this one, so i want to setup the return.

The "DistinctBy" Metod

public IEnumerable<TSource> DistinctBy<TSource, TKey>(
      IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

The Initial Setup For now i have something like this(I'm using Autofac's Moq, Automock functionality):

List<Product> listProduct = new List<Product>{ product1, product2 };
mock.Mock<IHelpers>()
    .Setup(r => r.DistinctBy<List<BeautyBoutiqueArticle>, int>(It.IsAny<List<BeautyBoutiqueArticle>>(), It.IsAny<Func<List<BeautyBoutiqueArticle>, int>>()))
    .Returns(ieList)
    .Verifiable();

But it's not working. It's displaying errors like:

The best overloaded method match for.... has some illegal arguments, and/or Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable>'

Community
  • 1
  • 1
DarkJoy
  • 11
  • 1
  • 3

1 Answers1

1

First of all moq required that you can moq interface methods or virtual methods . So first thing to do is do interface or virtual method. Your static method is not mockable

EDITED

If your method is not static then do the following and you dont need verifiable

mock.Mock<Helpers>().Setup(r => r.DistinctBy(It.IsAny<IEnumerable<TSource>>(), It.IsAny<Func<TSource, TKey>>())).Returns(ieList);
Dan Hunex
  • 5,172
  • 2
  • 27
  • 38
  • Sorry about that, my method is not static. I've updated the code. Also, the IHelpers class contains an interface for this method, so, i'm mocking the interface for the method. – DarkJoy Jul 29 '13 at 21:40
  • I've already tried something like that. That approach returns couple of errors: --- Error 7 The type arguments for method .... cannot be inferred from the usage. Try specifying the type arguments explicitly. --- Error 8 The type or namespace name 'TSource' could not be found (are you missing a using directive or an assembly reference?) --- Error 10 The type or namespace name 'TKey' could not be found (are you missing a using directive or an assembly reference?) Do you might know why is this happening? Thanks – DarkJoy Jul 30 '13 at 02:14