Tuesday, January 18, 2011

Use string.Join and Linq methods combo to facilitate easier unit testing

using System;
using System.Linq;

using Utilities;

using NUnit.Framework;




namespace TestTheUtilities
{
 [TestFixture]
 public class MyClass
 {  
  [Test]
  public void Fibonacci_is_ok()
  {
   Assert.AreEqual( "0,1,1,2,3,5,8",
               
         string.Join( ",", 
             Utils.FibonacciGenerator()
                  .Take(7).Select(x => x.ToString()).ToArray() )  

               );

   }

 } 
}


If it interest anyone, here's the fibonacci generator, just click to expand
using System;
using System.Collections.Generic;



namespace Utilities
{

 public static class Utils
 {
  public static IEnumerable<int> FibonacciGenerator ()
  {
   int prev = 0;
   int current = 1;
   
   for(;;)
   {
    yield return prev;
    
    int z = current;
    current = current + prev;
    prev = z;
   }
  }
 }
}


[EDIT]
The code above is not the easier way to compare collection, use CollectionAssert

No comments:

Post a Comment