<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Some Creativity</title>
	<atom:link href="http://blog.somecreativity.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.somecreativity.com</link>
	<description>Weblog of Siddharth Uppal</description>
	<lastBuildDate>Wed, 04 Mar 2009 19:55:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.somecreativity.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/c64b3831d98991fe5227914e0bc097fc?s=96&#038;d=http://s2.wp.com/i/buttonw-com.png</url>
		<title>Some Creativity</title>
		<link>http://blog.somecreativity.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.somecreativity.com/osd.xml" title="Some Creativity" />
	<atom:link rel='hub' href='http://blog.somecreativity.com/?pushpress=hub'/>
		<item>
		<title>Raising events in NMock</title>
		<link>http://blog.somecreativity.com/2009/03/04/raising-events-in-nmock/</link>
		<comments>http://blog.somecreativity.com/2009/03/04/raising-events-in-nmock/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 19:48:24 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=576</guid>
		<description><![CDATA[It is actually pretty easy to raise events using the latest release of NMock. You can basically use Expect.Once.On(bla).EventAdd(“SomeEvent”, Is.Anything) to specify that you expect an event handler to be added for “SomeEvent” event on bla object and fire that event using Fire.Event(“SomeEvent”). Here’s an example, minus any domain noise, that demonstrates the whole thing. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=576&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It is actually pretty easy to raise events using the latest release of NMock. You can basically use Expect.Once.On(bla).EventAdd(“SomeEvent”, Is.Anything) to specify that you expect an event handler to be added for “SomeEvent” event on bla object and fire that event using Fire.Event(“SomeEvent”).</p>
<p>Here’s an example, minus any domain noise, that demonstrates the whole thing.</p>
<p><span id="more-576"></span></p>
<p>Let’s say there’s an interface IJoker which exposes an event JokeMade.</p>
<p>	public interface IJoker<br />
	{<br />
		event EventHandler< JokeEventArgs > JokeMade;<br />
	}</p>
<p>	public class JokeEventArgs : EventArgs<br />
	{<br />
		public string Joke { get; private set; }</p>
<p>		public JokeEventArgs(string joke)<br />
		{<br />
			this.Joke = joke;<br />
		}<br />
	}</p>
<p>And there’s a class Batman which takes an object implementing IJoker as argument in its constructor.</p>
<p>	public class Batman<br />
	{<br />
		private IJoker joker;</p>
<p>		public Batman(IJoker joker)<br />
		{<br />
			this.joker = joker;<br />
			this.joker.JokeMade += (sender, e) =><br />
			{<br />
				this.LatestJoke = e.Joke;<br />
			};<br />
		}</p>
<p>		public string LatestJoke { get; private set; }<br />
	}</p>
<p>It hooks up a handler to the JokeMade event and updates the value of LatestJoke property with whatever joke is made.</p>
<p>So, here’s what the test would look like:</p>
<p>		[TestMethod()]<br />
		public void BatmanConstructorTest()<br />
		{<br />
			using (Mockery mocks = new Mockery())<br />
			{<br />
				IJoker mockJoker = mocks.NewMock< IJoker >();<br />
				Expect.Once.On(mockJoker).EventAdd(&#8220;JokeMade&#8221;, Is.Anything);</p>
<p>				Batman testBatman = new Batman(mockJoker);</p>
<p>				string expectedJoke = &#8220;Bug-free code!&#8221;;<br />
				Fire.Event(&#8220;JokeMade&#8221;).On(mockJoker).With(mockJoker, new JokeEventArgs(expectedJoke));</p>
<p>				Assert.AreEqual(expectedJoke, testBatman.LatestJoke);<br />
			}<br />
		}</p>
<p>Notice the call to EventAdd and Fire.Event. </p>
<p>That’s it, hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/576/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/576/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/576/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=576&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2009/03/04/raising-events-in-nmock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Interfaces and partial classes</title>
		<link>http://blog.somecreativity.com/2009/02/13/interfaces-and-partial-classes/</link>
		<comments>http://blog.somecreativity.com/2009/02/13/interfaces-and-partial-classes/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 20:03:40 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=570</guid>
		<description><![CDATA[What will happen when the following piece of code is compiled? class Program { static void Main(string[] args) { ICanMove monkey = new Monkey(); monkey.Move(); } } public interface ICanMove { void Move(); } public partial class Monkey : ICanMove { } public partial class Monkey { public void Move() { Console.WriteLine(&#8220;Moved&#8221;); } } Options: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=570&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>What will happen when the following piece of code is compiled?</p>
<p>	class Program<br />
	{<br />
		static void Main(string[] args)<br />
		{<br />
			ICanMove monkey = new Monkey();<br />
			monkey.Move();<br />
		}<br />
	}</p>
<p>	public interface ICanMove<br />
	{<br />
		void Move();<br />
	}</p>
<p>	public partial class Monkey : ICanMove<br />
	{<br />
	}</p>
<p>	public partial class Monkey<br />
	{<br />
		public void Move()<br />
		{<br />
			Console.WriteLine(&#8220;Moved&#8221;);<br />
		}<br />
	}</p>
<p><b>Options:</b></p>
<ol>
<li>Compiler error.</li>
<li>“Moved” will be printed.</li>
</ol>
<p><span id="more-570"></span></p>
<p>Answer is b.</p>
<p>How is it useful?</p>
<p>Well, we can apply the same concept to test code that relies upon an auto-generated proxy for a web-service.</p>
<p>Here’s an example to explain what I mean.</p>
<p>Let’s say you have a class that uses a web-service.</p>
<p>	public class ServiceUser<br />
	{<br />
		public void UseService(ServiceProxy proxy)<br />
		{<br />
			proxy.DoSomething();<br />
		}<br />
	}</p>
<p>The class definition for ServiceProxy was generated using a tool (e.g. WSDL).</p>
<p>	public partial class ServiceProxy<br />
	{<br />
		public void DoSomething()<br />
		{<br />
			// Some code here<br />
		}<br />
	}</p>
<p>In a test for UseService we want to avoid calling the actual web-service. There are various possible reasons why – performance, usage limits on the web-service, etc.</p>
<p>If we introduce an interface IService like the following:</p>
<p>	public interface IService<br />
	{<br />
		void DoSomething();<br />
	}</p>
<p>And modify ServiceProxy to implement that interface:</p>
<p>	public partial class ServiceProxy : IService<br />
	{<br />
		public void DoSomething()<br />
		{<br />
			// Some code here<br />
		}<br />
	}</p>
<p>And also modify ServiceUser.UseService to accept an object implementing that interface:</p>
<p>	public class ServiceUser<br />
	{<br />
		public void UseService(IService proxy)<br />
		{<br />
			proxy.DoSomething();<br />
		}<br />
	}</p>
<p>Then, to test UseService we can create a mock-object implementing IService and pass it into UseService method.</p>
<p>		[TestMethod()]<br />
		public void UseServiceTest()<br />
		{<br />
			using (Mockery mocks = new Mockery())<br />
			{<br />
				IService mockService = mocks.NewMock<iservice>();<br />
				Expect.Once.On(mockService).Method(&#8220;DoSomething&#8221;);<br />
				ServiceUser target = new ServiceUser();<br />
				target.UseService(mockService);<br />
			}<br />
		}</p>
<p>However it is a good idea to avoid making changes to the auto-generated code for ServiceProxy because they’ll be lost as soon as the proxy is re-generated using the tool.</p>
<p>So that’s where the concept I mentioned in the beginning can help.</p>
<p>Instead of modifying the auto-generated code, just introduce the following empty partial class definition.</p>
<p>	public partial class ServiceProxy : IService<br />
	{<br />
	}</p>
<p>The actual auto-generated ServiceProxy class definition stays the same as that generated by the tool:</p>
<p>	public partial class ServiceProxy<br />
	{<br />
		public void DoSomething()<br />
		{<br />
			// Some code here<br />
		}<br />
	}</p>
<p>That’s it and now you can safely test UseService.</p>
<p></iservice></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/570/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/570/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/570/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=570&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2009/02/13/interfaces-and-partial-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Preventing tracing of sensitive information in logs generated using .NET trace classes</title>
		<link>http://blog.somecreativity.com/2008/12/17/preventing-tracing-of-sensitive-information-in-logs-generated-using-net-trace-classes/</link>
		<comments>http://blog.somecreativity.com/2008/12/17/preventing-tracing-of-sensitive-information-in-logs-generated-using-net-trace-classes/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 21:04:18 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[trace]]></category>
		<category><![CDATA[sensitive information]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=563</guid>
		<description><![CDATA[If you have an application that deals with payment processing, social-security numbers, etc., there’s a possibility that such sensitive information can be written to log by a component in the application. While you need to take appropriate measures to ensure that the log files are sufficiently protected, you may also want to prevent such information [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=563&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you have an application that deals with payment processing, social-security numbers, etc., there’s a possibility that such sensitive information can be written to log by a component in the application. While you need to <a href='http://msdn.microsoft.com/en-us/library/ms733053.aspx'>take appropriate measures</a> to ensure that the log files are sufficiently protected, you may also want to prevent such information from being logged altogether. And if that’s the case, here’s something that can help.</p>
<p>TraceCheckingListener is a custom <a href='http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener.aspx'>TraceListener</a> which checks each incoming trace message for the presence of credit-card numbers and causes the trace to fail by throwing an exception if one is found. </p>
<p>	public class TraceCheckingListener : TraceListener<br />
	{<br />
		private const string CreditCardRegEx = @&#8221;(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})&#8221;;<br />
		private Regex regex;</p>
<p>		public TraceCheckingListener()<br />
		{<br />
			this.regex = new Regex(CreditCardRegEx, RegexOptions.Compiled);<br />
		}</p>
<p>		private bool ContainsCreditCardNumber(string text)<br />
		{<br />
			return (!String.IsNullOrEmpty(text)) &#038;&#038; this.regex.IsMatch(text);<br />
		}</p>
<p>		public override void Write(string message)<br />
		{<br />
			if (this.ContainsCreditCardNumber(message))<br />
				throw new InvalidOperationException(&#8220;Sensitive credit-card information cannot be logged.&#8221;);<br />
		}</p>
<p>		public override void WriteLine(string message)<br />
		{<br />
			if (this.ContainsCreditCardNumber(message))<br />
				throw new InvalidOperationException(&#8220;Sensitive credit-card information cannot be logged.&#8221;);<br />
		}<br />
	}</p>
<p>It currently checks for Visa, MasterCard, American Express, Discover, Diners Club and JCB credit-cards.</p>
<p>TraceChecker is a small utility class which can be instantiated in a C# using block to install the TraceCheckingListener while the using block executes and remove it when it’s done.</p>
<p>	public class TraceChecker : IDisposable<br />
	{<br />
		private TraceCheckingListener traceCheckingListener;</p>
<p>		public TraceChecker()<br />
		{<br />
			this.traceCheckingListener = new TraceCheckingListener();<br />
			Trace.Listeners.Insert(0, this.traceCheckingListener);<br />
		}</p>
<p>		#region IDisposable Members</p>
<p>		public void Dispose()<br />
		{<br />
			if (this.traceCheckingListener != null)<br />
			{<br />
				Trace.Listeners.Remove(this.traceCheckingListener);<br />
				this.traceCheckingListener = null;<br />
			}<br />
		}</p>
<p>		#endregion<br />
	}</p>
<p>One way to make use of these classes is to introduce the following class in your unit-test suite assembly.</p>
<p>[TestClass]<br />
public class TraceCheckerInstaller<br />
{<br />
	private static TraceChecker traceChecker;</p>
<p>	[AssemblyInitialize]<br />
	public static void InstallTraceChecker(TestContext context)<br />
	{<br />
		traceChecker = new TraceChecker();<br />
	}</p>
<p>	[AssemblyCleanup]<br />
	public static void UninstallTraceChecker()<br />
	{<br />
		if (traceChecker != null)<br />
		{<br />
			traceChecker.Dispose();<br />
			traceChecker = null;<br />
		}<br />
	}<br />
}</p>
<p>InstallTraceChecker will be <a href='http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assemblyinitializeattribute(VS.80).aspx'>called only once</a> when the assembly containing the unit-tests is loaded so we use the opportunity to install the custom trace-listener. UninstallTraceChecker will be <a href='http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assemblycleanupattribute(VS.80).aspx'>called once</a> when the assembly is being unloaded which we use to remove the custom trace-listener.</p>
<p>Alternately, you may also utilize the following approach in individual unit-tests.</p>
<p>		[TestMethod]<br />
		public void MyTestMethod()<br />
		{<br />
			using (new TraceChecker())<br />
			{<br />
				// Write code to test whatever you want to test here.<br />
				// This test will fail if any method called from here<br />
				// attemps to trace sensitive information to the log.<br />
			}<br />
		}</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/563/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=563&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/12/17/preventing-tracing-of-sensitive-information-in-logs-generated-using-net-trace-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Mocking functions taking variable number of args using C# params keyword</title>
		<link>http://blog.somecreativity.com/2008/12/16/mocking-functions-taking-variable-number-of-args-using-c-params-keyword/</link>
		<comments>http://blog.somecreativity.com/2008/12/16/mocking-functions-taking-variable-number-of-args-using-c-params-keyword/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 23:01:41 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[nmock]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=558</guid>
		<description><![CDATA[Consider the following interface that takes a variable number of arguments in its Add method. public interface IAdder { string Add(params string[] items); } And consider that we have to test the following function which invokes Add with two arguments. public string AddStrings(string one, string two, IAdder adder) { return adder.Add(one, two); } The expectation [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=558&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Consider the following interface that takes a variable number of arguments in its Add method.</p>
<p>	public interface IAdder<br />
	{<br />
		string Add(params string[] items);<br />
	}</p>
<p>And consider that we have to test the following function which invokes Add with two arguments.</p>
<p>		public string AddStrings(string one, string two, IAdder adder)<br />
		{<br />
			return adder.Add(one, two);<br />
		}</p>
<p>The expectation created below is incorrect:</p>
<p>				string[] args = new string[] { &#8220;FOO&#8221;, &#8220;BAR&#8221; };<br />
				IAdder adder = mocks.NewMock<iadder>();<br />
				string expected = &#8220;FOOBAR&#8221;;</p>
<p>				Expect.Once.On(adder).Method(&#8220;Add&#8221;).With(args).Will(Return.Value(expected));</p>
<p>				string actual;<br />
				actual = target.AddStrings(args[0], args[1], adder);<br />
				Assert.AreEqual(expected, actual);</p>
<p>It will cause NMock to generate the following exception because NMock is expecting two distinct arguments to Add with values “FOO” and “BAR” instead of an array of strings containing “FOO” and “BAR”.</p>
<blockquote><p>NMock2.Internal.ExpectationException occurred<br />
  Message=&#8221;unexpected invocation of adder.Add()\r\nExpected:\r\n  1 time: adder.Add(equal to \&#8221;FOO\&#8221;, equal to \&#8221;BAR\&#8221;), will return \&#8221;FOOBAR\&#8221; [called 0 times]\r\n&#8221;</p></blockquote>
<p>You need to change the expectation so that NMock compares the string-array.</p>
<p>				Expect.Once.On(adder).Method(&#8220;Add&#8221;).With(Is.EqualTo(args)).Will(Return.Value(expected));</p>
<p>That’ll do the trick.</p>
<p></iadder></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/558/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/558/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/558/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=558&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/12/16/mocking-functions-taking-variable-number-of-args-using-c-params-keyword/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Fluently mocking fluent APIs</title>
		<link>http://blog.somecreativity.com/2008/12/15/fluently-mocking-fluent-apis/</link>
		<comments>http://blog.somecreativity.com/2008/12/15/fluently-mocking-fluent-apis/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 03:22:48 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[fluent]]></category>
		<category><![CDATA[nmock]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=551</guid>
		<description><![CDATA[The best thing about fluent-style APIs is that they are readable and flow easily. Consider the following for example: customer.NewOrder .With(1, &#8220;ONE&#8221;) .With(2, &#8220;TWO&#8221;) .With(3, &#8220;THREE&#8221;) .PriorityRush(); The API used above is clearly more readable than: Order o1 = new Order(); customer.AddOrder(o1); OrderItem item1 = new OrderItem(1, &#8220;ONE&#8221;); o1.Add(item1); OrderItem item2 = new OrderItem(2, &#8220;TWO&#8221;); [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=551&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The best thing about <a href='http://www.martinfowler.com/bliki/FluentInterface.html'>fluent-style APIs</a> is that they are readable and flow easily. Consider the following for example:</p>
<p>			customer.NewOrder<br />
				.With(1, &#8220;ONE&#8221;)<br />
				.With(2, &#8220;TWO&#8221;)<br />
				.With(3, &#8220;THREE&#8221;)<br />
				.PriorityRush();</p>
<p>The API used above is clearly more readable than:</p>
<p>			Order o1 = new Order();<br />
			customer.AddOrder(o1);<br />
			OrderItem item1 = new OrderItem(1, &#8220;ONE&#8221;);<br />
			o1.Add(item1);<br />
			OrderItem item2 = new OrderItem(2, &#8220;TWO&#8221;);<br />
			o1.Add(item2);<br />
			OrderItem item3 = new OrderItem(3, &#8220;THREE&#8221;);<br />
			o1.Add(item3);<br />
			o1.SetRush();</p>
<p>Another reason I like them is that fluent style APIs are easier to pick up. You can rely on intellisense to guide you more as you have to worry about lesser number of class and method names.</p>
<p>So they’re nice, but I hate to see code like the following that has to do a lot of setting up before you can actually make a call to the function you wish to test from your unit-test:</p>
<p>		[TestMethod()]<br />
		public void PlacePriorityOrderTest()<br />
		{<br />
			using (Mockery mocks = new Mockery())<br />
			{<br />
				int itemID = 42;<br />
				string itemDescription = &#8220;SOMETHING&#8221;;</p>
<p>				Program target = new Program();</p>
<p>				// Start setting up NMock expectations&#8230;<br />
				ICustomer customer = mocks.NewMock<icustomer>();<br />
				IOrderActions mockOrderActions = mocks.NewMock<iorderactions>();<br />
				Expect.Once.On(customer).GetProperty(&#8220;NewOrder&#8221;).Will(Return.Value(mockOrderActions));<br />
				IOrderActions mockOrderItemActions = mocks.NewMock</iorderactions><iorderactions>();<br />
				Expect.Once.On(mockOrderActions).Method(&#8220;With&#8221;).With(itemID, itemDescription).Will(Return.Value(mockOrderItemActions));<br />
				Expect.Once.On(mockOrderItemActions).Method(&#8220;PriorityRush&#8221;);<br />
				// End setting up NMock expectations&#8230;</p>
<p>				// Call the function we wish to test<br />
				target.PlacePriorityOrder(customer, itemID, itemDescription);<br />
			}<br />
		}</p>
<p>Here is the function that the test above is exercising:</p>
<p>		public void PlacePriorityOrder(ICustomer customer, int itemID, string itemDescription)<br />
		{<br />
			customer.NewOrder.With(itemID, itemDescription).PriorityRush();<br />
		}</p>
<p>The test is just making sure that the item-id and item-description passed to PlacePriorityOrder are used to create a new order with priority-rush. There’re probably going to be many tests that exercise the same fluent-API and they’d all be doing similar setting up of mock objects.</p>
<p>It would be better if the expectation was specified in a fluent manner as well.</p>
<p>		[TestMethod()]<br />
		public void PlacePriorityOrderTest2()<br />
		{<br />
			using (Mockery mocks = new Mockery())<br />
			{<br />
				int itemID = 42;<br />
				string itemDescription = &#8220;SOMETHING&#8221;;</p>
<p>				Program target = new Program();</p>
<p>				MockCustomer mockCustomer = MockCustomer.Record(mocks);<br />
				mockCustomer.NewOrder.With(itemID, itemDescription).PriorityRush();</p>
<p>				target.PlacePriorityOrder(mockCustomer.Start(), itemID, itemDescription);<br />
			}<br />
		}</p>
<p>Notice the call to MockCustomer.Record to return a mock ICustomer instance that can be used to record calls to various methods that the test expects to be made. Also note that mockCustomer.Start is used to retrieve the mock ICustomer instance that’s actually used by the function under test.</p>
<p>The <a href='http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=somecreativity&amp;DownloadId=4180'>zip archive here</a> contains code demonstrating how this can be done.</p>
<p></iorderactions></icustomer></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/551/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=551&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/12/15/fluently-mocking-fluent-apis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Testing methods that depend upon a singleton class</title>
		<link>http://blog.somecreativity.com/2008/12/11/testing-methods-that-depend-upon-a-singleton-class/</link>
		<comments>http://blog.somecreativity.com/2008/12/11/testing-methods-that-depend-upon-a-singleton-class/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 23:06:39 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[nmock]]></category>
		<category><![CDATA[private accessors]]></category>
		<category><![CDATA[singleton]]></category>
		<category><![CDATA[unit-test]]></category>

		<guid isPermaLink="false">http://blog.somecreativity.com/?p=541</guid>
		<description><![CDATA[Singleton is probably one of the most (mis-)used design patterns. In this article I intend to lay out a scenario and then demonstrate how we can go about testing methods that depend upon a singleton class. Finally I’ll recap the whole approach in a bulleted list for easy reference. Let’s restrict our problem to involve [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=541&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href='http://msdn.microsoft.com/en-us/library/ms998558.aspx'>Singleton</a> is probably one of the most (mis-)used design patterns. In this article I intend to lay out a scenario and then demonstrate how we can go about testing methods that depend upon a singleton class. Finally I’ll recap the whole approach in a bulleted list for easy reference.</p>
<p>Let’s restrict our problem to involve just 2 classes for the purpose of this article. Assume there’s already a class named Transaction and we’re interested in testing its CompleteTransaction method. </p>
<p>	public class Transaction<br />
	{<br />
		public void CompleteTransaction()<br />
		{<br />
			DeviceManager.Instance.OpenCashDrawer();<br />
		}<br />
	}</p>
<p>In our test we plan to ensure that CompleteTransaction calls the OpenCashDrawer method of DeviceManager. </p>
<p>	public sealed class DeviceManager<br />
	{<br />
		private static readonly DeviceManager instance = new DeviceManager();</p>
<p>		private DeviceManager()<br />
		{<br />
		}</p>
<p>		public static DeviceManager Instance<br />
		{<br />
			get<br />
			{<br />
				return instance;<br />
			}<br />
		}</p>
<p>		public void OpenCashDrawer()<br />
		{<br />
			// Code for opening cash-drawer will go here.<br />
			Console.WriteLine(&#8220;CashDrawer opened&#8230;&#8221;);<br />
		}</p>
<p>	}</p>
<p>DeviceManager is a singleton and there lies our problem. If there was an interface that DeviceManager implemented and CompleteTransaction took an object implementing that interface as argument we could have used NMock to mock that interface and created expectations in our test to expect a call to its OpenCashDrawer method when CompleteTransaction is called. We want to reduce the code churn so another alternative is needed. Changing the singleton semantics of DeviceManager or changing the CompleteTransaction method’s signature – are alternatives which will potentially require modification of a lot of code and testing it.</p>
<p>But having an interface in the picture will make our job easier so here’s what we can do. </p>
<ol>
<li><strong>Extract interface:</strong> We can extract an interface containing all the methods contained in DeviceManager class. Let’s say, we’re going to call it IDeviceManager.</li>
<li><strong>Change types:</strong> We can then modify the type of static instance field and static Instance property to be IDeviceManager instead of DeviceManager.</li>
<li><strong>Plant mock:</strong> In our test for CompleteTransaction method if we could somehow plant a mock object implementing IDeviceManager in the DeviceManager.instance field, we can then create an expectation in our test saying that expect a call to OpenCashDrawer method. </li>
</ol>
<p><strong>Extract interface</strong></p>
<p>This is easy to do in our example. In the real world, especially for a class that has been around for years, there could potentially be hundreds of methods. If that’s the case you have, take a look at the <a href='http://devexpress.com/Products/Visual_Studio_Add-in/Refactoring/'>DevExpress Refactor add-in for Visual Studio</a> which just requires you to right-click on a class and select “Extract interface”.</p>
<p>In our example, here’s what we end up with:</p>
<p>	public sealed class DeviceManager : IDeviceManager<br />
	{<br />
		private static readonly DeviceManager instance = new DeviceManager();</p>
<p>		private DeviceManager()<br />
		{<br />
		}</p>
<p>		public static DeviceManager Instance<br />
		{<br />
			get<br />
			{<br />
				return instance;<br />
			}<br />
		}</p>
<p>		public void OpenCashDrawer()<br />
		{<br />
			// Code for opening cash-drawer will go here.<br />
			Console.WriteLine(&#8220;CashDrawer opened&#8230;&#8221;);<br />
		}</p>
<p>	}</p>
<p>	public interface IDeviceManager<br />
	{<br />
		void OpenCashDrawer();<br />
	}</p>
<p>At this point all of your code should compile just fine.</p>
<p><strong>Change types</strong></p>
<p>We simply change the type of instance field and Instance property to be IDeviceManager.</p>
<p>	public sealed class DeviceManager : IDeviceManager<br />
	{<br />
		private static IDeviceManager instance = new DeviceManager();</p>
<p>		private DeviceManager()<br />
		{<br />
		}</p>
<p>		public static IDeviceManager Instance<br />
		{<br />
			get<br />
			{<br />
				return instance;<br />
			}<br />
		}</p>
<p>		public void OpenCashDrawer()<br />
		{<br />
			// Code for opening cash-drawer will go here.<br />
			Console.WriteLine(&#8220;CashDrawer opened&#8230;&#8221;);<br />
		}</p>
<p>	}</p>
<p>	public interface IDeviceManager<br />
	{<br />
		void OpenCashDrawer();<br />
	}</p>
<p>Again at this point the code should compile just fine. If it doesn’t, as would be the case where you have code that saves an instance of DeviceManager in a local variable before doing stuff with it, you’ll have to refactor that code to get rid of all compilation errors. </p>
<p><strong>Plant mock</strong>
<p>How do we plant a mock-object in the private static field DeviceManager.instance? </p>
<ol>
<li>We start by making use of the private-accessors feature of Visual Studio 2008. Right-click on DeviceManager class and select “Create Private Accessors”. You can read more about private accessors <a href='http://msdn.microsoft.com/en-us/library/ms184807.aspx'>here</a>. The basic idea is that a DeviceManager_Accessor class will be created mirroring the public methods of DeviceManager but additionally also exposing its private and protected fields. Internally a DeviceManager_Accessor object manages a DeviceManager object and forwards all method calls and field accesses to it. You can also create private-accessors from the Visual Studio command-prompt using “publicize ”.</li>
<li>We write our test to create a mock-object implementing IDeviceManager and plant it in the DeviceManager’s static instance field using DeviceManager_Accessor.
<p>				IDeviceManager mockDeviceManager = mocks.NewMock< IDeviceManager>();<br />
				DeviceManager_Accessor.instance = mockDeviceManager;</p>
</li>
<li>But there’s something to watch out for. It is possible that this test runs as part of a suite of tests so you want to ensure that DeviceManager.Instance returns a normal DeviceManager object after your test has finished executing. It is not sufficient to set DeviceManager_Accessor to null – you must restore the DeviceManager_Accessor.instance field to whatever its value was before you set it to a mock object. Since we want to ensure that the instance static field gets reset even if our test code throws an exception, we do the resetting in a finally block. Here’s what the test-method’s body would look like.
<p>			using (Mockery mocks = new Mockery())<br />
			{<br />
				// save<br />
				IDeviceManager prevDeviceManager = DeviceManager_Accessor.instance;</p>
<p>				try<br />
				{<br />
					// plant<br />
					IDeviceManager mockDeviceManager = mocks.NewMock<idevicemanager>();<br />
					DeviceManager_Accessor.instance = mockDeviceManager;</p>
<p>					// TODO: write test code here.<br />
				}<br />
				finally<br />
				{<br />
					// restore<br />
					DeviceManager_Accessor.instance = prevDeviceManager;<br />
				}<br />
			}</p>
<p></idevicemanager></li>
</ol>
<p><strong>The test</strong></p>
<p>Now that we have everything in place, let’s write the actual test code. Before calling CompleteTransaction, we create an NMock expectation to ensure that OpenCashDrawer is called on the mock IDeviceManager object.</p>
<p>		[TestMethod()]<br />
		public void CompleteTransactionTest()<br />
		{<br />
			using (Mockery mocks = new Mockery())<br />
			{<br />
				// save<br />
				IDeviceManager prevDeviceManager = DeviceManager_Accessor.instance;</p>
<p>				try<br />
				{<br />
					// plant<br />
					IDeviceManager mockDeviceManager = mocks.NewMock<idevicemanager>();<br />
					DeviceManager_Accessor.instance = mockDeviceManager;</p>
<p>					// we expect OpenCashDrawer to be called<br />
					Expect.Once.On(mockDeviceManager).Method(&#8220;OpenCashDrawer&#8221;);</p>
<p>					// the actual<br />
					Transaction target = new Transaction();<br />
					target.CompleteTransaction();<br />
				}<br />
				finally<br />
				{<br />
					// restore<br />
					DeviceManager_Accessor.instance = prevDeviceManager;<br />
				}<br />
			}</p>
<p>		}</p>
<p>Run the test and it should pass. Change the body of CompleteTransaction method to not make a call to OpenCashDrawer and the test should fail.</p>
<p><strong>Recap of the approach</strong></p>
<ol>
<li>Extract an interface from the singleton class.</li>
<li>Modify the singleton class to implement the newly created interface.</li>
<li>Modify the type of the static field (= VB.NET shared) holding a reference of the singleton class, and the return-type of the method/property returning the singleton to be same as the newly created interface.</li>
<li>Generate an accessor assembly for the assembly containing the singleton class for use in your unit-tests.</li>
<li>Write your unit-test to create a mock object implementing the newly introduced interface and plant it in the static field of the singleton class.</li>
<li>Create necessary expectations on various methods on the newly introduced interface which you expect to be called by the function under test.</li>
<li>Once your test is finished, ENSURE that the previous singleton is restored (using finally block).</li>
</ol>
<p>If, however, you’re in the process of writing a new singleton class in your project, consider introducing an interface and create a façade which everyone would use to obtain an instance of your class implementing that interface. This will probably save you from having to revisit this article in the future <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href='http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=somecreativity&amp;DownloadId=4148'>Click here</a> to download a zip archive containing the code shown in this article.</p>
<p></idevicemanager></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/541/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=541&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/12/11/testing-methods-that-depend-upon-a-singleton-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Pex to test VB.NET code</title>
		<link>http://blog.somecreativity.com/2008/12/02/using-pex-to-test-vbnet-code/</link>
		<comments>http://blog.somecreativity.com/2008/12/02/using-pex-to-test-vbnet-code/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 02:55:29 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Tech/Hacks]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[pex]]></category>
		<category><![CDATA[vb.net]]></category>

		<guid isPermaLink="false">http://siddhu.wordpress.com/?p=537</guid>
		<description><![CDATA[In an ideal world one would write unit-tests before writing any new code following the tenants of TDD. In reality it is quite common to have to rely on a legacy library to do some heavy lifting. Pex is a great new tool available from Microsoft Research that can be used to generate unit-tests automatically. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=537&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In an ideal world one would write unit-tests before writing any new code following the tenants of TDD. In reality it is quite common to have to rely on a legacy library to do some heavy lifting. <a href='http://research.microsoft.com/Pex/'>Pex</a> is a great new tool available from Microsoft Research that can be used to generate unit-tests automatically. It is smart in that it runs the function you wish to test trying to exercise all possible code paths and ultimately generates unit-tests that can be used to test that function.</p>
<p>Using Pex is as easy as right-clicking on a function in Visual Studio and selecting “Run Pex Explorations”. Pex takes a little while running your function and then displays a table with various values that can be used to test your function.</p>
<p>However if your legacy code happens to be in VB.NET, you cannot just right-click on a function to have Pex generate all unit-tests for you. So that’s where I hope this article will help you.</p>
<p>First, let’s define a scenario. Imagine there’s a class called Transaction and a class called PaymentMethod. A transaction contains various payment-methods. A PaymentMethod indicates whether it requires the cash-drawer to be opened or not (e.g. it doesn’t make sense to pop cash-drawer for a credit-card while it does for cash and debit-card). There’s a read-only property PopCashDrawer on Transaction which returns true if any of the payment-methods requires the cash-drawer to be opened.</p>
<p>Public Class PaymentMethod</p>
<p>	Private mPopCashDrawer As Boolean</p>
<p>	Public Property PopCashDrawer() As Boolean<br />
		Get<br />
			Return Me.mPopCashDrawer<br />
		End Get<br />
		Set(ByVal value As Boolean)<br />
			Me.mPopCashDrawer = value<br />
		End Set<br />
	End Property</p>
<p>End Class</p>
<p>Public Class Transaction</p>
<p>	Private mPaymentMethods() As PaymentMethod</p>
<p>	Public Property PaymentMethods() As PaymentMethod()<br />
		Get<br />
			Return Me.mPaymentMethods<br />
		End Get<br />
		Set(ByVal value As PaymentMethod())<br />
			Me.mPaymentMethods = value<br />
		End Set<br />
	End Property</p>
<p>	Public ReadOnly Property PopCashDrawer() As Boolean<br />
		Get<br />
			Dim pop = False<br />
			For Each pm As PaymentMethod In Me.PaymentMethods<br />
				pop = pop OrElse pm.PopCashDrawer<br />
			Next<br />
			Return pop<br />
		End Get<br />
	End Property</p>
<p>End Class</p>
<p>To have Pex generate unit-tests for you, here’s what you need to do:</p>
<ul>
<li>First to get started writing unit-tests, just right-click on Transaction in Visual Studio and select “Create Unit Tests”. Make sure you select “Create a new Visual C# project” for Output Project in the dialog that pops up.</li>
<li>Next, in the generated class TransactionTest add the following parameterized unit-test (PUT). This guides Pex to come up with different values of arguments to this method which will exercise all code-paths in PopCashDrawer property. Transaction.PopCashDrawer depends upon the PaymentMethods so we take the array of PaymentMethods as argument to our PUT and set it on the transaction before calling PopCashDrawer. The PexAssume.IsNotNull line further guides Pex to say that we don&#8217;t really care about the case when transaction is null because we&#8217;re really interested in testing PopCashDrawer method.
<p>	[PexMethod]<br />
	public bool PopCashDrawerPUT(Transaction transaction, PaymentMethod[] paymentMethods)<br />
	{<br />
		PexAssume.IsNotNull(transaction);<br />
		transaction.PaymentMethods = paymentMethods;<br />
		return transaction.PopCashDrawer;<br />
	}</p>
</li>
<li>Next, just right-click on PopCashDrawerPUT and select “Run Pex Explorations”. Pex will then display a table with various values of arguments and the results it got in each case.</li>
<li>However since the VB assembly is separate from the C# test-project, Pex will display an icon indicating that it didn’t explore some methods because they were uninstrumented.</li>
<li>Make sure you include all methods displayed as uninstrumented and run Pex explorations again.</li>
<li>This time around Pex would show 7 different test-cases that it identified.</li>
<li>A file named TransactionTest.PopCashDrawerPUT.g.cs would be generated containing unit-tests for those 7 cases. Take a look at that class to see how much work it saved you.</li>
<li>You can run the generated unit-tests by going to <em>Test-&gt;Run-&gt;All Tests in Solution</em> from the main-menu in Visual Studio.</li>
<li>Pex would discover inputs which cause PopCashDrawer to throw a NullReferenceException. Determining fixes for those cases is left as an exercise to the reader <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </li>
</ul>
<p><a href='http://research.microsoft.com/Pex/downloads.aspx'>Download</a> and try out Pex, if you haven&#8217;t already!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/537/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=537&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/12/02/using-pex-to-test-vbnet-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Mocking indexers with NMock</title>
		<link>http://blog.somecreativity.com/2008/11/25/mocking-indexers-with-nmock/</link>
		<comments>http://blog.somecreativity.com/2008/11/25/mocking-indexers-with-nmock/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 00:42:45 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Tech/Hacks]]></category>
		<category><![CDATA[indexers]]></category>
		<category><![CDATA[nmock]]></category>

		<guid isPermaLink="false">http://siddhu.wordpress.com/?p=534</guid>
		<description><![CDATA[Indexers allow objects to behave like arrays. Dictionary class in .NET, for example, provides an indexer that allows the retrieval of the item from the dictionary that corresponds to a particular key. There are two ways you can go about mocking indexers defined on interfaces when using NMock. You can use the Get property to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=534&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Indexers allow objects to behave like arrays. Dictionary class in .NET, for example, provides an indexer that allows the retrieval of the item from the dictionary that corresponds to a particular key.</p>
<p>There are two ways you can go about mocking indexers defined on interfaces when using NMock. </p>
<ol>
<li>
<p>You can use the <strong>Get</strong> property to describe what should be returned when a particular parameter is passed. The following expectations for example, cause “xxx” to be returned when foo[“aaa”] or foo[“bbb”] is called.</p>
<p>Expect.Once.On(foo).Get["aaa"].Will(Return.Value(&#8220;xxx&#8221;));<br />
Expect.Once.On(foo).Get["bbb"].Will(Return.Value(&#8220;xxx&#8221;));</p>
<p>
This approach works fine in most circumstances. However you are required to provide all the values with which the indexer can be invoked. This presents a problem in the scenario where you need to return a particular value irrespective of the value of the input parameter.
</p>
</li>
<li>
<p>Indexers are implemented under the hood as methods so NMock’s support for mocking methods can be used to mock indexers. An indexer definition is munged by the compiler to a pair of get_Item and set_Item methods. When you call foo[“aaa”], it is munged by the compiler to a call to the get_Item method on foo with “aaa” as the argument.</p>
<p>So here’s what you can do to make sure that “xxx” is returned irrespective of the value of the parameter passed to the indexer.</p>
<p>Stub.On(foo).Method(&#8220;get_Item&#8221;).Will(Return.Value(&#8220;xxx&#8221;));</p>
<p>Now any call of the form foo[&lt;BLAH&gt;] will return “xxx”.</p>
</li>
</ol>
</p>
</p>
</p>
</p>
</p></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/534/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=534&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/11/25/mocking-indexers-with-nmock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>NMock expectations for functions accepting &#8220;ref&#8221; and &#8220;out&#8221; arguments</title>
		<link>http://blog.somecreativity.com/2008/11/17/nmock-expectations-for-functions-accepting-ref-and-out-arguments/</link>
		<comments>http://blog.somecreativity.com/2008/11/17/nmock-expectations-for-functions-accepting-ref-and-out-arguments/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 22:28:48 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[expectations]]></category>
		<category><![CDATA[nmock]]></category>
		<category><![CDATA[out keyword]]></category>
		<category><![CDATA[ref keyword]]></category>

		<guid isPermaLink="false">http://siddhu.wordpress.com/?p=529</guid>
		<description><![CDATA[There appears to be inadequate documentation on setting up expectations in NMock for methods that accept arguments by reference using “out” and “ref” keywords. Here is a quick note to give an example demonstrating how it can be done. Consider the following interface: public interface IFoo { void Bar(out int a, ref int b); } [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=529&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There appears to be inadequate <a href='http://www.nmock.org/advanced.html'>documentation</a> on setting up expectations in <a href='http://nmock.org'>NMock</a> for methods that accept arguments by reference using “out” and “ref” keywords. Here is a quick note to give an example demonstrating how it can be done.</p>
<p>Consider the following interface:</p>
<p>	public interface IFoo<br />
	{<br />
		void Bar(out int a, ref int b);<br />
	}</p>
<p>“Bar” method takes one “out” parameter and another “ref” parameter.</p>
<p>To start mocking &#8220;IFoo&#8221; you would obviously first create a new mock object implementing interface “IFoo”.</p>
<p>	IFoo aFoo = mocks.NewMock< IFoo >();</p>
<p>We store it in a variable named “aFoo”.</p>
<p>Here’s how you would set up an expectation to ask NMock to expect a call to method “Bar” on “aFoo” object with an “out” parameter and a “ref” parameter with 2 as its value.</p>
<p>	Expect.Once.On(aFoo)<br />
		.Method(&#8220;Bar&#8221;).With(Is.Out, 2)<br />
		.Will(new SetNamedParameterAction(&#8220;a&#8221;, 10),<br />
			new SetNamedParameterAction(&#8220;b&#8221;, 20));</p>
<p>The actions specified in the “Will” part cause the “out” and “ref” parameters to be set to values 10 and 20 respectively after “Bar” is called on “aFoo”.</p>
<p>	int a, b = 2;<br />
	aFoo.Bar(out a, ref b);</p>
<p>	// At this point &#8220;a&#8221; will be set to 10 and &#8220;b&#8221; will be set to 20 because<br />
	// of the expectation specified above.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/529/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/529/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/529/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=529&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/11/17/nmock-expectations-for-functions-accepting-ref-and-out-arguments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>
	</item>
		<item>
		<title>Automating windows forms UI testing</title>
		<link>http://blog.somecreativity.com/2008/11/06/automating-windows-forms-ui-testing/</link>
		<comments>http://blog.somecreativity.com/2008/11/06/automating-windows-forms-ui-testing/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 23:49:50 +0000</pubDate>
		<dc:creator>Sid</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tech/Hacks]]></category>
		<category><![CDATA[automated UI testing]]></category>
		<category><![CDATA[windows forms]]></category>

		<guid isPermaLink="false">http://siddhu.wordpress.com/?p=518</guid>
		<description><![CDATA[If you have been blessed with a windows-forms application that has business-logic invading the user-interface, I have something that’ll help you. The most practical approach in this situation is to rearchitect the business layer and switch the UI over in a piecemeal fashion. While you&#8217;re doing this, automated testing of the user-interface will make your [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=518&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you have been blessed with a windows-forms application that has <a href='http://stackoverflow.com/questions/223982/business-logic-invading-ui-in-a-large-winforms-app'>business-logic invading the user-interface</a>, I have something that’ll help you. The most practical approach in this situation is to rearchitect the business layer and switch the UI over in a piecemeal fashion. While you&#8217;re doing this, automated testing of the user-interface will make your job a lot faster compared to manual testing.</p>
<p>For the purpose of this article let us consider a simple Windows Forms application (download link below). The application allows the user to provide two inputs and then either add them or subtract them. Simple, right?</p>
<p><b>The application</b><br />
<img src="http://siddhu.files.wordpress.com/2008/11/screenshot.png?w=304&#038;h=273" alt="screenshot" title="screenshot" width="304" height="273" class="alignnone size-full wp-image-517" /></p>
<p>Here’s the code for the event-handlers of interest to us:</p>
<p>		private void MainForm_Load(object sender, EventArgs e)<br />
		{<br />
			this.lblAnswer.Text = &#8220;0&#8243;;<br />
		}</p>
<p>		private void btnAdd_Click(object sender, EventArgs e)<br />
		{<br />
			this.lblAnswer.Text = Convert.ToString(this.numericUpDown1.Value + this.numericUpDown2.Value);<br />
		}</p>
<p>		private void btnSubtract_Click(object sender, EventArgs e)<br />
		{<br />
			this.lblAnswer.Text = Convert.ToString(this.numericUpDown1.Value &#8211; this.numericUpDown2.Value);<br />
		}</p>
<p>The handler for the load event of the form just sets the answer label to display “0”. The handler for the click event of each of the buttons retrieves the selected values from the numeric drop-downs, applies the appropriate operation, and writes the result into the label. </p>
<p><b>The tests</b></p>
<p>In order to write tests for this application, you can start by right-clicking on the class of the form (in this case MainForm), and selecting “Create Unit Tests…”. Hit “OK” on the dialog that pops up to create unit-tests in a separate project. Another dialog will pop up asking for the name of the test project. Just hit “Create”.</p>
<p>This will cause Visual Studio to do some heavy lifting for us and generate accessors to allow us to call methods and properties defined on MainForm, from our tests. We don’t have to write code for accessors using the Reflection API ourselves – so this is extremely cool. Doing it on our own is quite painful (<a href='http://msdn.microsoft.com/en-us/magazine/cc163864.aspx'>proof</a>).</p>
<p>Delete all the tests marked with the TestMethod attribute in the generated class because we’re going to write our own.</p>
<p>The first one is pretty simple. We expect the answer label to display a “0” when the form is initially loaded – so let’s test that. </p>
<p>		///<br />
<summary>
		///A test for MainForm_Load<br />
		///</summary>
<p>		[TestMethod()]<br />
		[DeploymentItem("AppUnderTest1.exe")]<br />
		public void MainForm_LoadTest()<br />
		{<br />
			MainForm_Accessor target = new MainForm_Accessor();<br />
			target.MainForm_Load(null, null);<br />
			Assert.AreEqual(&#8220;0&#8243;, target.lblAnswer.Text, &#8220;Initial answer is zero&#8221;);<br />
		}</p>
<p>Notice that we can call MainForm_Load directly (no <a href='http://msdn.microsoft.com/en-us/library/system.reflection.aspx'>ConstructorInfo, MethodInfo – reflection stuff</a> required).</p>
<p>Once that’s done we can just check the text displayed in the answer label and make sure it is “0”.</p>
<p>We can take the same approach to call the click event handlers of the buttons and check the results for addition/subtraction.</p>
<p>Since there are various cases to test, I have a separate function GetTestTable that returns a two dimensional array where each row contains the two test-inputs, result of subtraction, and result of addition – in that order.</p>
<p>		public int[,] GetTestTable()<br />
		{<br />
			// Format of each row:<br />
			// A, B, (A-B), (A+B)<br />
			int[,] table =<br />
			{<br />
				{0, 0, 0, 0},<br />
				{10, 0, 10, 10},<br />
				{0, 10, -10, 10},<br />
				{-10, 0, -10, -10},<br />
				{0, -10, +10, -10},<br />
				{10, 10, 0, 20},<br />
				{-10, -10, 0, -20},<br />
				{-10, 10, -20, 0},<br />
				{10, -10, 20, 0}<br />
			};<br />
			return table;<br />
		}</p>
<p>Following is the function that actually does the testing. We basically process each row returned by GetTestTable one by one. First we set the two inputs on the numeric drop-downs. Next we call the click event-handlers of both buttons verifying what is in the answer label against what we expect. Again notice that we can directly invoke the event handlers and even access properties of the answer label (lblAnswer).</p>
<p>		///<br />
<summary>
		///A test for btnSubtract_Click<br />
		///</summary>
<p>		[TestMethod()]<br />
		[DeploymentItem("AppUnderTest1.exe")]<br />
		public void AddSubtractTest()<br />
		{<br />
			MainForm_Accessor target = new MainForm_Accessor();</p>
<p>			int[,] table = this.GetTestTable();</p>
<p>			for (int i = 0; i < table.GetUpperBound(0); i++)<br />
			{<br />
				int a = table[i, 0],<br />
					b = table[i, 1],<br />
					subtract = table[i, 2],<br />
					add = table[i, 3];</p>
<p>				target.numericUpDown1.Value = a;<br />
				target.numericUpDown2.Value = b;</p>
<p>				target.btnSubtract_Click(null, null);<br />
				int result = Convert.ToInt32(target.lblAnswer.Text);<br />
				Assert.AreEqual(subtract, result, String.Format(&#8220;Subtract {0} and {1}&#8221;, a, b));</p>
<p>				target.btnAdd_Click(null, null);<br />
				result = Convert.ToInt32(target.lblAnswer.Text);<br />
				Assert.AreEqual(add, result, String.Format(&#8220;Add {0} and {1}&#8221;, a, b));<br />
			}<br />
		}</p>
<p>To run these tests, select Test-&gt;Run-&gt;All Tests in Solution from the main-menu in Visual Studio. The “Test Results” window in Visual Studio should show that all tests passed.</p>
<p><strong>Summary</strong>
<p>There’re multiple ways to go about automating UI testing. You could use an automated testing tool like Mercury Quick Test. However if you want to take things into your own hands and take advantage of greater control, you could write your tests using NUnit or MS-Test and make PInvoke calls to send messages to various controls in the UI of your application under test. You could use the <a href='http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx'>SendKey API</a> in Windows.Forms too.</p>
<p>However if you want to take advantage of knowledge of the internals of the application under test, we have to use Reflection to set properties of the controls, invoke event handlers, call other methods and then test whether this resulted in the changes that we expected. This makes the job extremely painful. I hope this article shows how much easier it is if we leverage Visual Studio Team System to generate accessors for us.</p>
<p>I don’t see why the technique described above cannot be used to test WPF and Silverlight applications as well.</p>
<p><b>Download</b><br />
<a href='http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=somecreativity&amp;DownloadId=3678'>Click here</a> to download the code accompanying this article.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/siddhu.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/siddhu.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/siddhu.wordpress.com/518/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.somecreativity.com&blog=7388&post=518&subd=siddhu&ref=&feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.somecreativity.com/2008/11/06/automating-windows-forms-ui-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5f52292ae4f73466f86149f2c94d462a?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">siddhu</media:title>
		</media:content>

		<media:content url="http://siddhu.files.wordpress.com/2008/11/screenshot.png" medium="image">
			<media:title type="html">screenshot</media:title>
		</media:content>
	</item>
	</channel>
</rss>