How to constrain mocks for use with Complex Types

19. January 2012

Here are some tests to illustrate how to leverage RhinoMocks constraints. Notice that it is easier to get a passing test on failing code with a stub. The Strict mock will enforce the expectations at the time of the call, where the stub will only throw an exception on an AssertWasCalled. Due to this I would recommend that you explicitly do your setup and use strict mocks, or make sure to have the discipline to test those assertions.

 

With the method Matches() ,you can use any predicate or method call that returns a boolean. You cannot however use a lambda with a method body aka () =>{}. This will not compile.

[TestClass]

public class Tests

{

[TestMethod]
        public void Should_Allow_Constraint()
        {
            //Arrange
            var mock = MockRepository.GenerateStrictMock<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.First() is Test))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoIt();

            //Assert
            mock.VerifyAllExpectations();
            Assert.AreEqual("TestPass",result);
        }

        [TestMethod]
        public void Should_Enforce_Constraint_On_Strict_Mock()
        {
            //Arrange
            var mock = MockRepository.GenerateStrictMock<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.Any(t=> t is Test)))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoItWrong();

            //Assert
            mock.VerifyAllExpectations();
            Assert.AreEqual("TestPass", result);
        }

        [TestMethod]
        public void Should_Allow_Manual_Enforce_Constraint_On_Stub()
        {
            //Arrange
            var mock = MockRepository.GenerateStub<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => TestSomething(c)))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoItWrong();

            //Assert
            mock.AssertWasCalled(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.Any(t => t is Test))));
            Assert.AreEqual("TestPass", result);
        }

        private bool TestSomething(List<ITest> tests)
        {
            return true;
        }
    }

    public class Tester
    {
        private ITestExerciser _testExerciser;

        public Tester(ITestExerciser testExerciser)
        {
            _testExerciser = testExerciser;
        }

        public object DoIt()
        {
            return _testExerciser.DoSomething(new List<ITest>() {new Test()});
        }

        public object DoItWrong()
        {
            return _testExerciser.DoSomething(new List<ITest>() { new TestBase() });
        }
    }

    public class TestExerciser : ITestExerciser
    {
        public object DoSomething(List<ITest> args)
        {
            return null;
        }
    }

    public interface ITestExerciser
    {
        object DoSomething(List<ITest> args);
    }

    public class Test : TestBase
    {
       
    }

    public class TestBase : ITest
    {
        public int Id { get; set; }
    }

    public interface ITest
    {
        int Id { get; set; }
    }

C#, C# Helpful Functions, Testing, Unit Testing, RhinoMocks

Composing Complex Queries with LINQ to Entities

30. April 2011

We have all had those times where we have had to build chains on complex where statements, with several OR / AND operations. These make LINQ queries look really complex and most of the time need to be reused in several places. To clean this up and give us the ability to compose complex queries on the fly from say a UI filter or something similar give the following a try.

public class Test
    {
        public void Testing()
        {
            Expression<Func<Product, bool>> isRed = c1 => c1.Color == "Red";

            Expression<Func<Product, bool>> isCheap = c2 => c2.StandardCost < 10.0m;

            Expression<Func<Product, bool>> isClothing = c3 => c3.Class == "Clothing";

            Expression<Func<Product, bool>> isAcceptable = Utility.BuildOrElse(isRed, isCheap, isClothing);

            IQueryable<Product> products = null;
            var query = products.Where(isAcceptable);
        }

    }

    public class ParameterRebinder : ExpressionVisitor
    {

        private readonly Dictionary<ParameterExpression, ParameterExpression> map;



        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {

            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();

        }



        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {

            return new ParameterRebinder(map).Visit(exp);

        }



        protected override Expression VisitParameter(ParameterExpression p)
        {

            ParameterExpression replacement;

            if (map.TryGetValue(p, out replacement))
            {

                p = replacement;

            }

            return base.VisitParameter(p);

        }

    }

    public static class Utility
    {

        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {

            // build parameter map (from parameters of second to parameters of first)

            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);



            // replace parameters in the second lambda expression with parameters from the first

            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);



            // apply composition of lambda expression bodies to parameters from the first expression 

            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);

        }



        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.And);

        }



        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.Or);

        }

        public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {

            return first.Compose(second, Expression.Or);

        }

        public static Expression<Func<T, bool>> BuildAnd<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.And(expression));
        }

        public static Expression<Func<T, bool>> BuildOr<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.Or(expression));
        }

        public static Expression<Func<T, bool>> BuildOrElse<T>(params Expression<Func<T, bool>>[] conditions)
        {
            return conditions.Aggregate<Expression<Func<T, bool>>, Expression<Func<T, bool>>>(null, (current, expression) => current == null ? expression : current.OrElse(expression));
        }

    }

Adapted and added to from

http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx

Entity Framework, Data Access, C#, C# Helpful Functions, Productivity

LINQ, Lambda and the Learning Curve

3. January 2010

Been away for a while working on a 107,000 hour project. It isn?t done, but I am making time to blog and do my technical mentorship, because I have come to realize that there will always be high priority projects. You have to take the time to train and mentor during those projects because of that. Now on to the show.

I know that LINQ has received a massive welcome from the community and I have to say that it is a deserved on. On the whole it is a great addition to the language. I however don?t like one part of it. Verbose LINQ. I realize that it is more SQL like and that it is perceived to  shorten the learning curve, but I disagree. Lambdas are where the true power of LINQ sit and using verbose to me seems to focus you to learn LINQ one way so that you can re-learn it another.

I am going to focus on the Lambda side of LINQ simply out of preference. Keep an eye out here for the verbose VS. lambda death match, but that is a post for another time.

Lambda statements are actually fairly simple once you break them up.

SomeList.Where(c=>c.Id == someInt);

The above is the lambda conversion of this code block

foreach (Item item in SomeList)
{
    If(item.Id == soemInt)
        SomeOtherList.Add(item);
}

Lets break down the lambda so that this is a bit more clear.

c =>

This statement is declaring that the item in the list we are looking at is going to be held in the local variable named ?c?. This is no different than naming the variable in a for each loop ?c?. You can name your lambda variables more intuitively and I would encourage you to do so. Something like this.

SomeList.Where(menuItem => MenuItem.Id == someInt);

Once the object is declared you have the ability to use all of the members of that object. That is how we are able to use the ?Id? property to check something for a Boolean property. Selecting based on some Boolean expression is the most common use for Lambdas but not the only one.

List<SubMenu> submenus = SomeList.Select(menuItem => new SubMenu() 
                                                   {
                                                         ParentMenuId = menuItem.Id 
                                                   });

In this example we have created a submenu item from all the menu items in the list. We did this through the power of LINQ to let use change the output type of the selection at will. This is very usefull when you are creating items from other items. The code block that would represent is:

List<SubMenu> SubMenus = new List<SubMenu>();

foreach(MenuItem item in SomeList)
{
    SubMenu subMenu = new SubMenu();
    subMenu.ParentMenuId = item.Id;
    SomeOtherList.Add(subMenu);
}

To me this power is amazing. I have the ability to replace entire loops with a single line. The hit to readability is a concern but lambdas lend themselves to so many applications, and are key to LINQ so it should be part of the core toolset of a developer. If you use some sense and name your lambda variables intuitively you should get a lot of great millage out of LINQ without losing your readability.

C#, C# Helpful Functions, .NET

C# Functions that might help pt. 1

14. September 2009

When talking to a friend of mine we had the idea to do a blog series over C# functions that might help people if they don?t know about them. This will be categorized so you can keep up on it, and it will be once a week on Mondays. First I was going to start with ?continue?. Nest ifs inside a loop cause major performance issues in most applications but there are a few ways to avoid this. The MSDN definition of continue is ?The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.? . Here is the code snippet that we are going to clean up. ?Caution the following code is not suitable for young viewers or those that are faint of heart.?

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter != null)
                {
                    parameter.MethodName = "Something";
                    if (parameter.children != null)
                    {
                        foreach (var child in parameter.children)
                        {
                            if (child.MethodName == null)
                            {
                                child.MethodName = "Something";
                            }
                        }
                    }
                }
            }

I know right? We can clean this up by inverting the first if to a continue statement.

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                    if (parameter.children != null)
                    {
                        foreach (var child in parameter.children)
                        {
                            if (child.MethodName == null)
                            {
                                child.MethodName = "Something";
                            }
                        }
                     }
            }
We can still clean this up by inverting the children check to a continue statement.
IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                if (parameter.children == null) continue;
                foreach (var child in parameter.children)
                {
                    if (child.MethodName == null)
                    {
                        child.MethodName = "Something";
                    }
                }
            }

We can also do this to the if inside the second for each loop.

IEnumerable<ReflectionParameter> test = new List<ReflectionParameter>();

            foreach (var parameter in test)
            {
                if (parameter == null) continue;
                parameter.MethodName = "Something";
                if (parameter.children == null) continue;
                foreach (var child in parameter.children)
                {
                    if (child.MethodName != null) continue;
                    child.MethodName = "Something";
                }
            }

This is a much cleaner section of code but is not great. It still has a nested for each loop. which makes my insides scream, but we will attack that sort of nesting next week.

.NET, Productivity, C# Helpful Functions