That way the methods are grouped nicely and also displayed neatly when showed by intellisense. Below is an example of how I do that:
public interface ICategoryOne
{
string MethodOne();
int MethodTwo();
int MethodThree(string value);
}
internal class RealCategoryOne : ICategoryOne
{
private StringBuilder sb;
public RealCategoryOne(StringBuilder sb)
{
this.sb = sb;
}
public string MethodOne()
{
return "method one";
}
public int MethodTwo()
{
return sb.GetHashCode();
}
public int MethodThree(string value)
{
return value.Count();
}
}
public static class MyExtensionMethods
{
public static Func<StringBuilder, ICategoryOne> CategoryOneFactory = sb => new RealCategoryOne(sb);
public static ICategoryOne CategoryOne(this StringBuilder sb)
{
return CategoryOneFactory(sb);
}
}
With intellisense, the methods will be shown like:


Then to test these extension methods with Moq:
Mock<ICategoryOne> categoryOne = new Mock<ICategoryOne>();
categoryOne.Setup(c => c.MethodOne()).Returns("Moq method 1");
categoryOne.Setup(c => c.MethodTwo()).Returns(-555);
categoryOne.Setup(c => c.MethodThree(It.IsAny<string>())).Returns(-999);
StringBuilder sb = new StringBuilder();
MyExtensionMethods.CategoryOneFactory = prm => categoryOne.Object;
var test = sb.CategoryOne().MethodOne();
Assert.AreEqual(test, "Moq method 1");
Alternatively we can create a fake/dummy class for testing:
public class FakeCategoryOne : ICategoryOne
{
private StringBuilder sb;
public FakeCategoryOne(StringBuilder sb)
{
this.sb = sb;
}
public string MethodOne()
{
throw new NotImplementedException();
}
public int MethodTwo()
{
throw new NotImplementedException();
}
public int MethodThree(string value)
{
throw new NotImplementedException();
}
}
Then we change the factory above as:MyExtensionMethods.CategoryOneFactory = prm => new FakeCategoryOne(prm);
Reference:
http://blogs.clariusconsulting.net/kzu/how-to-mock-extension-methods/

No comments:
Post a Comment