Friday, September 21, 2007

Code snippets... yay!

I am starting on a new project without resharper... so i have to write alot more code than I am used to... enter VS intellisense code snippets!

Here is a very basic one I have for NMock;

<CodeSnippets xmlns="">
<CodeSnippet Format="1.0.0">
<Title>Create a NMock Test</Title>
<Description>Create a NMock Test using mocks to improve testability.</Description>
<Author>Rhys Campbell</Author>
<ToolTip>Replace with the type of interface of the mocked object.</ToolTip>
<ToolTip>Replace with the name of the mock object .</ToolTip>
<ToolTip>Replace with the type of the test object .</ToolTip>
<ToolTip>Replace with the name of the test object .</ToolTip>
<ToolTip>Replace with the name of the test method to be called .</ToolTip>
<Code Language="CSharp">
public void TestExpect()
// mock the dependency by way of interface
IMock $mockObject$ = new DynamicMock(typeof($IMockClass$));

// setting up values
$mockObject$.ExpectAndReturn("Mock object expected method call", "Mock object expected method return value"); //remove and replace with appropiate expectation. NB: NMock uses strings not strong naming for it method calls.

$TestObject$ $testObject$ = new $TestObject$(($IMockClass$) $mockObject$.MockInstance);
AssertEquals("Some sort of valid repsonse", $testObject$.$MethodToBeTested$()); //replace with approriate test

// Verify that mock expectations are met

(you may want to format that) ;)

As per the M$ site:

Before you can begin writing your code snippet, you must create an XML file with a .snippet file name extension.
To create a .snippet file

  1. On the File menu, click New and then click File.

  2. Click XML File and then click Open.

  3. On the File menu, click Save .

  4. In the Save as type box, select All Files (*.*).

  5. In the File name box, enter a file name with the .snippet file name extension.

  6. Click Save.

What they dont say that you should save it somewhere that VS will know where to find it. the easiest is My documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets\
this is where VS looks by deafult, this means you dont have to import it it is just ready to go.
so to get the code to work just type in:
in any C# file and *Bam* there is you intellisense code block ready to fill out.

this propbaly wont change you life but its certainly a nice to have, espeically without my blessed ReSharper...

For more info: Go to the MSDN site

-oh the imports staements dont work in C# so i cant import my testing namspaces which sucks...

No comments: