The official Fatica Labs Blog! RSS 2.0
# Wednesday, 21 March 2012

Some days ago I came in this issue regarding thread non-safety when using MoQ. So I simple create my own fork on GitHub and solved the issue, that was really easy to do, and as a result I obtained a Mock stable even when mocked methods are called from multiple threads. I created a bounch of test to prove that worked, here below one as a sample:

clip_image001

So with this I made the Mock thread safe at the infrastructure level, that mean no more strange NullreferenceException and others. But what if we want our mock not thread safe? I mean there could be situation in which we want to ensure the system under test calls a certain method from a single thread,  in other word we want the mock to explicitly require single thread access to certain methods. This could happen for example when we are mocking some UI components, but there is such situations every time the object we are mocking is intrinsically non thread safe and the SUT is multithreaded. So I extended the MoQ fluent language from the internal and I obtain something like…  the example below:

moqts

So in the setup phase we declare a method ( or a setter, or a getter, as usual ) to be SingleThread(). This yield a mock throwing when the method is called from a different thread from the one which did the setup.

If you are happy with this modifications ( you would for sure find helpful the thread safety by its own ) feel free to check out my code fork on GitHub, in any case I’m trying to have that modification pulled from the main stream.

Wednesday, 21 March 2012 15:53:26 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject | MoQ

# Thursday, 15 March 2012

I’ve already talked about the simple contract checking library here. I did a little improvement that allow us to write such a code:

public void DoSomethingWithCustomMessage(string arg1)
        {
            Contract.Expect(() => arg1)
                .Throw<Exception>("I'm unhappy to see that {0} is null")
                .WhenViolate
                .IsNotNull();
        }

 

Note than {0} is replaced with the name of the argument so the library is refactoring friendly and DRY. The only restriction is that the exception type must support a constructor with a single string argument. Obviously .Throw can be used fluently after each all Expect(). As another minor improvement, even the .Expect can be called now fluently more than once, so multiple check can be done fluently too. The entire repository is on Bitbucket here. In order to use the library you just have to include the single file, but is better to point the repository since the file version can change in subsequent releases.

Thursday, 15 March 2012 16:16:42 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject

# Wednesday, 29 February 2012

In this post I will show how to make testable something that ( at least me ) usually left as untested. I’m talking about the preparing phase of a console app, the checking arguments error reporting and so on. That logic is usually so simple that any good cow boy programmer would probably leave outside any unit testing. Unfortunately we should at least do some manually check that prove that logic working, and doing things manually is always silly. In this post we assume we have a working command line parsing library, and a mocking framework. Let see the cowboy code:

        static void Main(string[] args)
        {
            string optA,optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) => optA = k);
            set.Add("b=", (k) => optB = k);
            set.Add("h", (k) => { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA,optB);
            
        }

        private static void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        private static void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        private static void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }

So nothing special, the example is actually very simple, we have two mandatory parameters, a command line switch to print a long help. If one argument is missing a short help line must be presented. If all the parameters are provided, the DoTheJob() method should be called with the correct values.

Current code is not testable without hosting the console application as a process, and looking at the stdout to see what happen. Even by this strategy, we can not punctually check what is passed to DoTheJob. So we want to refactor the code, without adding any complexity to the app. So here below the proposed refactoring:

    public class Program
    {
        static void Main(string[] args)
        {
            new Program().Run(args);
        }
        public virtual void Run(string[] args)
        {
            string optA, optB;
            optA = optB = null;
            bool done = false;
            OptionSet set = new OptionSet();
            set.Add("a=", (k) => optA = k);
            set.Add("b=", (k) => optB = k);
            set.Add("h", (k) => { LongHelp(); done = true; });
            set.Parse(args);
            if (done)
                return;
            if (string.IsNullOrEmpty(optA) || string.IsNullOrEmpty(optB))
            {
                ShortHelp();
                return;
            }
            DoTheJob(optA, optB);

        }

        public virtual void DoTheJob(string optA, string optB)
        {
            //something interesting here
        }

        public virtual void LongHelp()
        {
            Console.Error.WriteLine("Long help here...");
        }

        public virtual void ShortHelp()
        {
            Console.Error.WriteLine("Short help here");
        }
    }

 

So pretty easy, we provide a non static method Run(), and all the internal function are declared virtual. This is a five minutes modification we could probably apply to any other code like this we have. The difference is that we can write some unit test, lets see how:

        [TestMethod]
        public void ShouldDisplayShortHelp()
        {
            var moq = new Mock();
            moq.CallBase = true;
            moq.Setup(k=>k.DoTheJob(It.IsAny(),It.IsAny()))
                .Throws(new InvalidProgramException("Should not call"));
            moq.Object.Run(new string[0]);
            moq.Verify(k => k.ShortHelp());
        }
        [TestMethod]
        public void ShouldDisplayLongHelp()
        {
            var moq = new Mock();
            moq.CallBase = true;
            moq.Setup(k => k.DoTheJob(It.IsAny(), It.IsAny()))
                .Throws(new InvalidProgramException("Should not call"));
            moq.Object.Run(new string[]{"-h"});
            moq.Verify(k => k.LongHelp());
        }
        [TestMethod]
        public void ShouldInvokeWithProperParameters()
        {
            var moq = new Mock();
            moq.CallBase = true;
            moq.Setup(k => k.DoTheJob("p1", "p2")).Verifiable();
            moq.Object.Run(new string[] { "-a=p1","-b=p2" });
            moq.Verify();
        }

 

I used the MoQ library, please note the Callbase set to true, because we are using the same object for driving and for expect calls. So in conclusion, we achieve a real unit test of something we sometimes left apart, we did that in memory, and even if the example is really trivial, the concept can be used in complex scenarios too. What about testing the inside part of DoTheJob()? well, if a good testing strategy is used, the internal part should be testable outside somewhere else, here we are  proving we can test the shell. 

Wednesday, 29 February 2012 21:47:36 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | CSharp | Programmin

# Tuesday, 28 February 2012

This is a post for myself, because I’m much more a cow boy programmer, and I know this is bad, even if sometimes results are apparently good. The leaking part in my code are usually unit tests, and there is no excuse about that, since it is necessary to change the approach on its root, for example writing the (failing) test before the real code. This is actually a design strategy, that eventually improve the reliability of the software and the portability of the software against other developers. The hardest part is that sometimes the boundary between unit testing and integration testing is apparently very thin: making that boundary better defined is part of the design process. I found this document, and I think is very useful to understand the common errors producing a non testable code, and the strategy to avoid them.

Tuesday, 28 February 2012 21:13:39 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | Programmin

# Monday, 23 January 2012

… without writing a LinqToSomething provider, of course. The Expression.<Func<T>> construction is sometimes a little frightening since we suppose to have to write some complex tree navigation in order to achieve the expression behavior, but this is not always true, there is scenarios in which we can use it without any complex tree visit. In this post we will see some real world examples using this strategy.

1) INotifyPropertyChanged without “magic strings”

This interface is implemented in its simplest form:

public string CustomerName
{
   get
   {
	   return this.customerNameValue;
   }
   set
   {
	   if (value != this.customerNameValue)
	   {
		   this.customerNameValue = value;
		   NotifyPropertyChanged("CustomerName");
	   }
   }
}

We can leverage Linq.Expression here by this simple base class:

class PropertyChangeBase: INotifyPropertyChanged
{
	protected void SignalChanged<T>(Expression<Func<T>> exp)
	{
		if (exp.Body.NodeType == ExpressionType.MemberAccess)
		{
			var name = (exp.Body as MemberExpression).Member.Name;
			PropertyChanged(this, new PropertyChangedEventArgs(name));
		}
	   else
		   throw new Exception("Unexpected expression");
   }
   #region INotifyPropertyChanged Members
   public event PropertyChangedEventHandler PropertyChanged = delegate { };
   #endregion
}

By deriving our class from this one, we can easily notify a property change by writing:

SignalChanged(()=>CustomerName);


This allow us to leverage intellisense, and it is refactoring friendly, so we can change the name of our property without pain. The first project I seen using this technique was Caliburn Micro, but I’m not sure is the only one and the first. Same technique is used here to test the INotifyPropertyChange behavior.

2) Argument Verification

Really similar to the problem above, we want to avoid:

static int DivideByTwo(int num) 
{
   // If num is an odd number, throw an ArgumentException.
   if ((num & 1) == 1)
	   throw new ArgumentException("Number must be even", "num");

   // num is even, return half of its value.
   return num / 2;
}


In this case we are typing NUM, that is the name of the argument, as a literal string which is bad. We would preferably write something like this:

public void DoSomething(int arg1)
{
	Contract.Expect(() => arg1)
       .IsGreatherThan(0)
       .IsLessThan(100);
;
}

That again give us intellisense and refactoring awareness. You can find he code for this helper class here, and a brief description in this post.

3) The MoQ mocking library

The MoQ library is a .NET library for creating mock objects easy to use that internally leverage Linq.Expression to achieve such a readable syntax:

   mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
       .Returns(true)
       .AtMostOnce();

4) A generic Swap function:

The simplest way in creating a generic Swap function in c# is:

void Swap<T>(ref T a, ref T b)
{
   T temp = a;
   a = b;
   b = temp;
}

Unfortunately, this won’t work if we want swap two property of an object, or two elements of an array. We would like to write something like this:

   var t = new Test_() { X = 0, Y = 1 };
   Swapper.Swap(() => t.X, () => t.Y);
   Assert.AreEqual(0, t.Y);
   Assert.AreEqual(1, t.X);

or with arrays:

    int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Swapper.Swap(() => array[0], () => array[1]);
    Assert.AreEqual(2, array[0]);
    Assert.AreEqual(1, array[1]);

We can achieve this by a simple helper class using Linq.Expression:

public class Swapper
{
        public static void Swap(Expression<Func<T>> left, Expression<Func>T>> right)
        {
            var lvalue = left.Compile()();
            var rvalue = right.Compile()();
            switch (left.Body.NodeType)
            {
              case ExpressionType.ArrayIndex:
                  var binaryExp = left.Body as BinaryExpression;
                  AssignTo(rvalue, binaryExp);
                  break;

              case ExpressionType.Call:
                  var methodCall = left.Body as MethodCallExpression;
                  AssignTo(rvalue, methodCall);
                  break;
				  
              default:
                  AssignTo(left, rvalue);
                  break;
          }

          switch (right.Body.NodeType)
          {
              case ExpressionType.ArrayIndex:
                  var binaryExp = right.Body as BinaryExpression;
                  AssignTo(lvalue, binaryExp);
                  break;

              case ExpressionType.Call:
                  var methodCall = right.Body as MethodCallExpression;
                  AssignTo(lvalue, methodCall);
                  break;

              default:
                  AssignTo(right, lvalue);
                  break;
          }
      }

      private static void AssignTo<T>(T value, MethodCallExpression methodCall)
      {
          var setter = GetSetMethodInfo(methodCall.Method.DeclaringType,methodCall.Method.Name);
          Expression.Lambda<action>(
              Expression.Call(methodCall.Object, setter, Join(methodCall.Arguments, Expression.Constant(value)))
          ).Compile()();
      }

      private static Expression[] Join(ReadOnlyCollection<expression> args,Expression exp)
      {
          List<expression> exps = new List<expression>();
          exps.AddRange(args);
          exps.Add(exp);
          return exps.ToArray();
      }

      private static MethodInfo GetSetMethodInfo(Type target, string name)
      {
          var setName = Regex.Replace(name, "get", new MatchEvaluator((m) =>
          {
              return m.Value.StartsWith("g")?"set":"Set";
          })
          ,RegexOptions.IgnoreCase);
          var setter = target.GetMethod(setName);
          if (null == setter)
          {
              throw new Exception("can't find an expected method named:" + setName);
          }
          return setter;
      }

      private static void AssignTo<T>(Expression<Func<T>> left, T value)
      {
          Expression.Lambda<Func<T>>(Expression.Assign(left.Body, Expression.Constant(value))).Compile()();
      }

      private static void AssignTo<T>(T value, BinaryExpression binaryExp)
      {
          Expression.Lambda<Func<T>>(Expression.Assign(Expression.ArrayAccess(binaryExp.Left, binaryExp.Right), Expression.Constant(value))).Compile()();
      }
  }

This code leverages a samples by Takeshi Kiriya, I just added the ability in handling array to his own the original code.

5) Unit testing the presence of an attribute

Thomas Ardal talks in this post about how to easily unit test the presence of an attribute on a method of a class,  useful for example in MVC scenarios, or in others AOP circumstances.

A test leveraging his strategy is written as below:

    var controller = new HomeController();
    controller.ShouldHave(x => x.Index(), typeof(AuthorizeAttribute));

So we show five different simple application, I hope you find here some inspiration for your works, and feel free to write about your own ideas and enrich the list.

Monday, 23 January 2012 16:05:16 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
C# | CodeProject | Linq

# Monday, 16 January 2012

Here below a list of tools and libraries I consider necessary to carry on my USB key in order to be operative everywhere in a very little time:

  1. SharpDevelop
  2. NHibernate
  3. Caliburn(Micro)
  4. NInject
  5. Kaxaml
  6. SQLite
  7. Rad Software Regular Expression Designer
  8. ILSpy
  9. FlyFetch
  10. log4net

SharpDevelop

Is probably the single OS replacement for MS Visual Studio. Install and start to using it in term of minutes thanks to xcopy deploy. It reads projects in the same format of the original one ( since it uses thestandard framework libraries for reading/writing projects ).

NHibernate

If you can see a way to model the DB you want to use, then NH is probably the best OR/M existing in the .NET environment. As soon you have some confidence with it, it is very easy to start modeling our objects, expecially with the 3.2.x version that does not require anymore to write hbms.

Caliburn Micro

If you write UI using some XAML dialect ( WPF/SILVERLIGHT/WP7/ the new coming Win8 ) and you like MVVM, you have to look at it. Very easy to boostrap, with coroutine support embedded, I would like to use it even for an Hello World application Smile

NInject

An easy to learn DI framework. Easy and very intuitive to configure, it has some function to allow multiple components to be injected as array, and to configure dependencies from external modules. I choose it not only, but also for the wonderful home page Smile

Kaxaml

A pad to learn and test XAML, with intellisense and preview as you type. Like xamlpad, but much better.

SQlite

An embedded file based database. It handles concurrent access consistently, easy to interface with NHibernate. Unfortunately it is a native solution, so it works only in fully trusted environments.

Rad Software Regular Expression Designer

there is a lot of regex testing tool, but this is the one I use, so…

ILSPy

The open source replacement for reflector, It comes from the same team who create SharpDevelop. It has all the features the standard reflector has, but not yet a real plugin environment.

FlyFetch

Is the tool I use when I need to display in UI a very long recordset, and I want to page it without rewrite every day the same code.

log4net

To use in all application, even the simplest: logManager.GetLogger(GetType()).Info(“Hello World”); Smile It is probably the .NET logger existing from the early days, with a lot of appenders already written and tested.

 

So this is my list, of course, another survival pre condition is having an internet access, and the StackOverflow help Smile. There is no NUnit nor a Mocking library ( as for example, Moq) since both can be replaced by custom test and mocks, but of course, if there is still place on the USB Winking smile

Monday, 16 January 2012 19:39:06 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | Programming

My Stack Overflow
Contacts

Send mail to the author(s) E-mail

Tags
profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2019
Felice Pollano
Sign In
Statistics
Total Posts: 157
This Year: 0
This Month: 0
This Week: 0
Comments: 127
This blog visits
All Content © 2019, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano
Nike Winkels Nederland Outlet Nike Nederland Store Outlet Nike Nederland 2015 Outlet Nike Outlet Online Nike Sneakers Outlet