You are on page 1of 27
21apps | and the Point is? Unit Test SharePoint Solutions - The Basics Beginners Guide to Test Driven Web Part Development Andrew Woodward Beginners Guide to Test Driven Web Part Development Table of Contents Unit Testing SharePoint Solutions — The Basics Initial Information.. Platform Frameworks and tools .. Nunit. 3 TestDriven.Netisnssssissnnstinsnsnasienensnanitisnensnianntisenensntinnensnnennaesnnsse Test 1. Unit Testing a Web Partssjssstisnineeiansnatisnensnsnitiussensnisnnsiaenansnsineses Welcome Web Part..susssstsnsnsntianensnstitiissnensnianntisnsisnsnninnesnaenaesnnsse Step 1. Test Project ..essssnnsstinsnsnatienensnsniatineiensniennaeisenensnnnesnnenaesnsnsed Step 2, Welcome class j.sisstsnsnsnstisnensnsnistinseiensninensnisisnsienentisesnneniaesnsise 7 8 .10 11 13 Step 3. Making the tests fail Step 4. Fix the failing test. Step 5. Add more tests, fix them and repeat Step 5. Testing new functions/features.. Step 6. Revisit the original request..cn:mmmnenmimntntimmineeinennenmanannimnnnennen TT Step 7. Creating the web part 19 20 25 26 27 Creating the Web Part in a few easy steps. Step 8. Completing the story. Conclusion. Revision History.. 26 August 2008 V1.0 Page 2 of 27 Beginners Guide to Test Driven Web Part Development Unit Testing SharePoint Solutions - The Basics This document provides an introduction to unit testing web parts within SharePoint 2007; this is a beginner's guide and as such does not aim to address some of the more challenging issues you will face as you develop your SharePoint solutions (we will be covering these in our future more advanced white papers) but aims to get you thinking about how to develop with testability in mind. The fact that you are even readinga white paper entitled ‘Unit Testing SharePoint Solutions’ is very encouraging. We make the assumption that you have an understanding of Unit Testing, have done some before and would like to get going with SharePoint — if you haven't we provide links to relevant articles and blogs that will provide background information. Initial Information Platform The following technologies and versions are used throughout this white paper Windows SharePoint Services v3 Microsoft Office SharePoint Server 2007 Windows Server 2008 Visual Studio 2008 Although the examples are based on the current release of SharePoint and Windows Server most of the techniques will be valid for Windows SharePoint Services V2, SharePoint Portal Server 2003, Windows Server 2003 and Visual Studio 2005, All development examples will be based on Cf. Frameworks and tools NUnit is a unit-testing framework Nunit forall Net languages. Initially ported from JUnit, the current As part of our testing we will use NUnit as our unit testing production release, version 24, is framework as this provides us with a very well understood and the fifth major release of this easy to explain testing syntax that has been adopted by most xUnit based unittesting tool for other test frameworks on the .Net platform. Microsoft NET. Itis written entirely in C# and has been http://www.nunit.or completely redesignedto take advantage of many NET Articles on NUnit and an introduction to Unit Testing with NUnit | language features, for example are fairly common, We think that this article by Roy Osherove custom attributes and other explains things very well. reflection related capabilities Introduction to Test-driven development with NUnit and the NUnit-Add-in ~ Roy Osherove You could also start to look though the links on Darrell Norton’s blog post on .Net Test Driven Development which is a very valuable resource. 26 August 2008 V1.0 Page 3 of 27 Beginners Guide to Test Driven Web Part Development TestDriven.Net Although not required we personally find that the small investment in the TestDriven.Net Visual Studio Add-in makes life significantly easier when doing test driven development. http://www.testdriven.net Test 1. Unit Testing a Web Part Test Driven Development (TDD) follows the mantra; 1. Write a test that fails 2. Make it work 3. Repeat I’ve excluded the refactoring and the removal of duplication for brevity. We are going to adopt this approach; however before we can get to this we need to understand what it is we are developing. Welcome Web Part In our example we will look at a very simple welcome web part. The user story for this would read something like: As a power user I want to display a customisable time aware welcome message so that it can be added to the portal and provide a customised message to the portal users. As a developer we can estimate the effort and discuss the best ways to do this, we find out from these discussions that the user actually wants to be able to add this welcome message to a number of Web Part Pages and also be able to configure the message displayed. They would also like the message to vary depending on the time of day so we define a number of tasks 1. Develop web part 2. Provide custom property value that has shared storage 3. Provide a format for the message that allows it to alter based on the time it is displayed The following steps will walk through in detail how we approach the development and unit testing of our web part. Asa developer we have already worked out the basic design of the solution we will have a simple class library that will perform the logic and a web part that will call this to render the text, Step 1. Test Project We're doing TDD so we need to create our Test Project first. Yes we do this before we start doing any web part code as TDD will drive the development. 26 August 2008 V1.0 Page 4 of 27 Beginners Guide to Test Driven Web Part Development 1. Load Visual Studio and create a new C# class project and solution as in Figure 1. Create Unit Test Project and Solution LA zx oft type Templates: 5 Vial Ca Visual Studio installed templates Windows Web (Bwndows Fos toplcaton Gass bray Smart Deve [Ag]WPF Roptcation [GB WPF Browser Appkcation Office (Bconsole Aepcation BHEnoty Proiet Database GaWindows Service “SE WPF Custom Contra Livery Reporting SAMPF User Control trary Bivens nr Corte ibeny Siveriht Test My Templates wer Workfiow: {search Onine Templates, \weebulder sf) Other Languages 3) Other Prowect Types 1) Test Projexe [ Rrroed Fer coatha 8 G¥ dos brar (AI GRET Fronewarr33) Name [owtet aces Locate: fC agleshereFoniDev =] sense Soliton tlane; [AgleSharePortDev UnkTests Basic | Cheate drectory For solution a] on Figure 1. Create Unit Test Project and Solution 2. Add a reference to the NUnit.framework by right clicking on the project and choosing Add Reference, as in Figure 2, Add reference to NUnit framework 3. If you are using TestDriven. Net also add the NUnit.framework.extensions to make the NUnit test GUI available from the right click menu. 26 August 2008 V1.0 Page S of 27, Beginners Guide to Test Driven Web Part Development Axl ET | com | Projects | Bronse | Recent | Conponent Name Runtine = rantcore 2.0.50 tunt.core-extensons wo funticoresterFores W209 runt.coretess v2.0.5 runt ontenions tests 2.0.80 runt tres 2.0.50 runt feces tests v2.0.0 sic E unit. framewark.extensions unit framework.tests unitumocks 2.0.50 ‘unit.mocks.tests ¥2.0.50 unit 2.0.50 unit. tests 2.0.50 unit utl : aad Figure 2. Add reference to NUnit framework Fig2. Add reference to NUnit framework 4, Rename our class to match the class that we intend to test, if you rename the file this will also update the class declaration to match. You should now have a class similar to Figure 3. Initial project code. (Jnamespace UnitTest .Basic.Test { f) public class welcome Figure 3, initial project code 5. Add code for our first test as in Figure 4, Our first Test a. Add a using statement for NUnit.Framework b. Add the [TestFixture] attribute to the class declaration @), This tell NUnit that this class has tests to be run, 26 August 2008 V1.0 Page 6 of 27 Beginners Guide to Test Driven Web Part Development c. Add anew Test itis recognised good practice to name your tests using the Method, Scenario, Behaviour syntax as this aid both the developer to think about what they are trying to test but also to highlight what has broken if the test should go Red in the future. using NUnit.Framework ® namespace UnitTest Basic. Test { [TestPixture] public class welcome { [Test] public void GetMessage_ValidParameter_ReturnsMessagg () { Figure 4. Our first test 6. Your code should look similar to that shown above. As a developer we have had to think about how our solution will work before we can construct the test method. Our thought process here was along the lines of a. Ineed a welcome message b. The method to get this will need some parameter(s) passed as it is configurable c. Iwant my first test to return a valid message 7. Now looking back at what the mantra stated we are looking to write a test that initially fails, the test we have written above will pass (go ahead try it-if you have TestDriven.Net installed just right click on the project and choose Run Tests), You could add a default Assert.Fail command to this test to ensure it fails. Step 2. Welcome class People are often divided at this point as to how literally they take the idea of writing your tests first, and allowing the tests to drive out your interface. As this is a basic introduction | will assume that youare in the latter camp and we will setup our Welcome class manually. 26 August 2008 V1.0 Page 7 of 27 Beginners Guide to Test Driven Web Part Development 1, Add a new C# Class project to the solution called UnitTest.Basic, our namespace here is to help organise the code between the different white papers — your namespace will often reflect you organisation and project. 2. Rename the default Classi.cs to Welcome.cs and allow the code to be updated. 3. Add a Public method to you class called GetMessage with one String parameter, you code should look something like Figure 5. Welcome class code using Syster []namespace UnitTest .Basic { ES public class welcome ( public string GetMessage(string message} ( ® throw new Exception("Not yet implemented"); Figure 5. Welcome class code 4. You will note that I have added an Exception to show this method has not yet been implemented), You could also use System.NotimplemtedException used by Visual Studio. throw new Notimplement edexception Step 3. Making the tests fail Now we have a class and method against which to test we write our tests. A quick check to ensure we have not done anything silly (CTRL*SHIFT#B to build the solution). 1. Add a Project reference to our UnitTest Basic project to our UnitTest Basic.Test project. Your solution should look similar to Figure 6. Add project reference. 26 August 2008 V1.0 Page8 of 27 Beginners Guide to Test Driven Web Part Development LT xix er | com Propets once | Recect | By Solution ‘AgleSharePointDev,UnitTests.B SB untrest base 3. [ Properties > a References 2) Welcame.cs = Hl Unitrest.pasic.Test Si» [a Properties ae System “System. Core “Si System.Data Ll -S System, Data DataSetéxtensi © System.Xinl Figure 6. Add project Reference 2. We can now fill in our test method with code to call out welcome message. Asa developer we can make a call on how the message is constructed based on the discussion on the user story. Listing 1. Initial Test —GetMessage_ValidParameter_ReturnsMessage namespace UnitTest.Basic. Test { (Test Fixture) public class Welcome i [rest] public void GetMessage_ValidParaneter_ReturnsMessage 1 Bae. 12 wale ev Bas: string message = “Welcome to our SharePoint site. Ascert.AreBqual ("Good Agternocn, "+ message: welcome. GetNessage (message ) 3. You will see that we are only looking to do smalll steps here. We have made a call to our Welcome method and have Asserted that the returned message should be our message prefixed with Good Afternoon, 26 August 2008 v1.0 Page 9 of 27 Beginners Guide to Test Driven Web Part Development 4, Run the tests and you should now get a big Red failed warning as in Figure 7. Written a test that fails. 3 ‘=i le on _tveg Tt Toke Heo [FW GeonshasParbanaghthasPonter Unto Monten = Agia eeiderdghsheetnier, oe GSistiet tiarcebe tonto OE tse il ERGRRREE WE Gotten vebdPaomee:Ftwreiesss) Tay Carer 1 TedsRun 1 Folee 1 lroed 0 Shaped 0 Run Tie: D156 [cain | Tes ld of Agi lesharePotneDey) 134 leshareposnepey. UnieTests, ss Returnedensace() 15 ‘VagilesharePointDev\ agideShareFointDev.UnitTests. lseste\mascTese. ine 18 ®@ e-Teat\Beleane “ 2) {Er seen [Tet NR] Cosco 0] CneleEver] Tare] Lon Covelaed TeetCamss 1 ets fonet Foes) Tm DiS Figure 7. Written a test that fails 5. From the NUnit console we can see which test failed from the tree view but also from the error description D which also show the error message we stubbed out earlier. You can also get additional information about the error from the details pane ©. Step 4. Fix the failing test We have defined an initial test; we now need to make the code pass this test. Repeating our mantra for TDD we are on the Make it work step. 1. Write a test that fails 2. Make it work 3. Repeat In this example we are going to play a bit of devil's advocate and really do the minimum amount of code needed to make this pass, often developers new to unit testing will scoff at this approach and those that are more experienced may take slightly bigger steps. For this document however we are working through the process in deta 26 August 2008 v1.0 Page 10 of 27 Beginners Guide to Test Driven Web Part Development 1. Replace the code in your welcome class, this really is doing the minimum needed to pass the test throw new Exception ("Not yet implenented” with return "Good Afternoon, Welcome to our SharePoint site." 2, Run the tests again and you should see green as in Figure 8 Passed Initial Test. le Ye Broo Tos Tals Heb [eviaitracP ai eo ighShacPont es Teas BasaiiriTont| Ursteat @ visksne (@ GotlerepevakPacrnte,Retmnierge ntl Uingfase saci Tou foe Tene TeetCaree 1 Teste Rure 1 Fakes 0 Ignored © Skpad 0. Run Tew: 015, [sno | Teste Figure 8. Passed Initial Test What does this tell you about what we have done so far? If you're thinking its green that means it works you really should go back and have another look on Google for an article on Unit Testing. If you thinking the code is not really doing what I wanted it to do and we need more tests your well on your way to understanding what TDD is all about. Step S. Add more tests, fix them and repeat Let’s add another test and see what happens, the code should allow us to pass in a message which is returned along with the welcome greeting so let’s try that next. 1. Add another test to the Welcome TestFixture as in Figure 9. Add alternative message test ©); this will be a copy of the first test but using a different message parameter. Your code should look something like this. 26 August 2008 v1.0 Page 11 of 27 Beginners Guide to Test Driven Web Part Development [TestFixture] public class welcome ( [test] public void GetMessage_ValidParameter_ReturnsMessage () 1a 2Welcome welcome = new Basic.Welcome(); string message = "Welcome to our SharePoint site."; Assert AreBqual("Good Afternoon, " + message, welcome. GetMessage (message) ) ; t PaO) public void GetMessage_ValidAlternativeParameter_ReturnsMess| Basic.lclcone welcome = new Basic.ticlcone(); string message - "Welcome to our TDD site."; Assert AreBqual ("Good Afternoon, " + message, welcone.GetMessage (message) ) : Figure 9, added alternative message test 2. Run the tests again, Don’t fix the code yet - we are looking to have a failing test that we can fix, You should see something similar to Figure 10 Alternative message test failing. If you try to write the test and fix the code in the same step you will find yourself going back to break the test just to make sure it does what you want, You should now have 1 passed test and11 failed test DD, you will also see for the failed test exactly what the problem was. The text we expected was not the same as that returned @ 26 August 2008 v1.0 Page 12 of 27 Beginners Guide to Test Driven Web Part Development ror) Te Yow Dok et Ta tsb Either, Geeta ea eo) iT ME Gesinon VaaataatiePaenne,Neowstie:| Tax Caeme 2 TedRun 2 Fakeae 1 bpmrnd 0 Sepa 0 Rin Tine 171 @ Scatesap Vasant, Rewrlionsge a [iveraracceer_pevucnonescege() in \aatlesiarePoincbev\ agi ledharePoinctey.UnitTests, jante\ nicest. Banic-Teet\Gelcene.ca! lise. 20 Figure 10, Alternative Message Test failing 3. We can again fix the code fairly easily by replacing the line, we can rerun the tests after this and both tests should now pass. return "Good Afternoon, Welcone to our SharePoint site." with return "Good Afternoon, " + message The approaches we have taken in the steps above really do form the basis of doing Test Driven Development. We have not added any extra code that is not needed, we have tests that can be run again and again to ensure our code still works as needed and we have the confidence that we could refactor our code and as long as the tests are still green we know we have not broken anything. Step 5. Testing new functions/features As this is a SharePoint targeted document we have prefixed the word feature with function as we do not want to confuse this with SharePoint Features which is the subject of a whole other document, Looking at our user story and tasks we need to now look at creating a function that returns a greeting based on the date and time. We could just write some code that based the message on the current date time of the machine; however this would make testing difficult as we would need to run the tests in the morning afternoon and evening to ensure our code worked. So with Test Driven Development in mind we will create a method that accepts a time and returns the text appropriately. 1. We should have had a conversation with our customer/product owner by now to discuss the requirements for the time based greeting. We'll assume the outcome of this conversation was the following pseudo-code: * If time > 5.00 am and < 12.00 pm say ‘Good morning’ * Iftime > 12,00pm and 6.00pm say ‘Good afternoon’ * else say ‘Good evening’ 26 August 2008 v1.0 Page 13 of 27 Beginners Guide to Test Driven Web Part Development 2. Add the first test for method GetTimeBasedGreeting Tools like ReSharper make the to check the morning greeting. If you're getting into generation of these methods TDD now you may actually write the test with the very easy and significantly method and let Visual Studio generate the method for improve your development you. efficiency. 3. You should end up with a Test similar Figure 11, where | Mibultuunsletbrainscom/resharper we are testing for the boundary of 5.00am. ) [Test] public void GetTimeBasedGreet ing Morning _ReturnMorningGreet ing () { Basic.Welcome welcome = new Basic.Welcome(); TimeSpan timespan = new Timespan(5,0,0) AsSert.AreEqual ("Good morning", welcome .GetTineBasedGreet ing (timespan) ); Figure 11, Now Test GotTimeBasodGreeting_Morning_ReturnMorningGrocting 4, Your welcome class should not look something like Figure 12. GetTimeBasedGreeting initial implementation public class Welcome { public string GetMessage (string message) { return "Good Afternoon, " + message; public string GetTimeBasedGreeting(Timespan timespan} { throw new Not ImplementedException () 3 Figure 12, GetTimeBasedGreeting initial implementation 5. Running the tests should give you 2 Green passed and 1 Red failed tests, which is what we expect, our code has not broken the existing tests but our new test is expected to fail as we have not coded it yet. 6. Again we are only looking to write enough code each time to make our tests work, so completion of the logic will take us a few iterations, but we do this one step ata time - at this point you really are doing TDD © - your method should look something like Listing 2. GetTimeBasedGreeting 26 August 2008 v1.0 Page 14 of 27 Beginners Guide to Test Driven Web Part Development listing 2. Get | method \eBasedGreeting ~ In public string GetTime! fl edGresting (TimeSpan timeSpan string greeting = Af (timespan >= now Mmespan(5,0,0 { greeting = “Good morning"; ) return greeting; b 7. Continue by adding tests for the following a, Time 11.59am gives “Good morning” b, Time 12.00pm gives “Good afternoon” . Time 5.59pm gives “Good afternoon” 4d. Time 6.00pm gives “Good evening” fe, Time 4.59 gives “Good evening” We have effectively done some bounds checking of our code, we could pick any random time within each greeting but that would not have been very effective use of our tests, 8. After you write each test you should get the Red light, Write code, Green light. You may find that when you add a test your code already passes —as will be the case when you add a test for the 11.59am method above. This will happen sometimes the key is that would have made a statement as a developer of how you expect the code to function, You should hopefully end up with something like the Text Fixture in Listing 3. Text Fixture listing 3. Test Fixture (reetrixture] public clas public void GetMeseage_ValidParameter Returnstessage fl Basic.Welcame welcome ~ new Basic. Welcome: ctring message ~ "Welcome to our SharePoint site." ext-Aretqual ("Good Afternoon, " | message welcene.Getessage (message: (rect) public i void GetNessage_ValidAlternativeParaneter_ReturneMessage Basic.Welcame welcome ~ new Basic. elcome: string meccage - "Helcone to or TDD site." ext -Rretqual ("Good Afternoon, Message (nessage oeage welcome void GetTimeBasedGreeting MorningStart_ReturnMorningGreeting Basic.Welcome welcome = new Basic, Welcome: 26 August 2008 v1.0 Page 15 of 27 Beginners Guide to Test Driven Web Part Development Timespan timespan ~ new Timespan(S,0,0) ; Assert AreEqual ("Good morning” welcome .GetTimeBasedGreeting (timespan ) (rest) public Yold GetTumenasedsreeting Morningend_ReturMorningsreeting; Basic.Weloame welcome - new Basic. elcome: Timespan timespan ~ now Timespan(11, 59, 0 Aesert AreEqual ("Good morning”, velcone.GetTimeBazedGresting timespan} , (rest) public void GetTimeRazedGrecting_AfternoonStart_ReturnAgternoonGreeting i Welcome welcome ~ new Baste. come ‘Tamespan timespan ~ new Timespan(12, 0, 0) Aesert -AreEqual ("Good afternoon” welcome .GetTimeBasedGreeting |timespan} ) (rect) public void GetTimenasedsreeting_Afternoonsnd Returnatternoonsreeting fl Basic.Weloame we me ~ new Basic. Welcome ‘Timegpan timespan - now TimeSpan(17, 59, 9 Assert AreEqual ("Good afternoon” welecne ‘ePimeDazedcreeting (timespan) (rest) public void GetTimeBasedtresting_BveningStart_ReturnBveningGrecting fl Welcome welcome ~ new Rasie. welcome ‘Tamespan timespan ~ new Timespan(18, 0, 0) Resort ArsEqual ("Good evening”, welcome .GetTimeBasedGreeting |timespan’ ) (rest) public void GetTimeBasedGresting_BveningEnd_RoturaBveningGresting, fl Basic.Weloame welcome ~ new Basie. welcome: Timespan timespan ~ new TimeSpan(4, 89, 0) Rosert AreEqual ("Good evening”, welcome .GetTimeBasedGreeting |timespan} And you code should look something like Listing 4. Welcome Class Listing 3. Welcome Class public clase Welcome 1 public string GetNessage (string message! i return "Good Afternoon, " + messages public string GetTimeBasedGresting (TimeSpan timeSpan 26 August 2008 v1.0 Page 16 of 27 Beginners Guide to Test Driven Web Part Development string greeting ="; if (timespan >= now Timespan(5,0,0 th pan < new TimeSpan(12, 0,0 1 greeting = "Good morning" ) £ (timespan >= new TimeSpan (12,0 timespan < new Timespan/18,0,0 greeting = "Good afte ) else 1 greeting = "Good evenin: ) return greeting: 9. At this point you may be starting to question the fact you have over double the amount of unit test code to production code. This is not uncommon, the key thing to remember is you can now safely refactor your code and know that it will continue to work as originally required if the tests all go green. This is a great feeling, especially as you get towards the end of a project. Step 6. Revisit the original request With all this testing of the time based greeting we may have forgotten what we were doing this for! We need to go back to our original test and the GetMessage method and refactor that to make use of our new TimeBasedGreeting, 1. Update the GetMessage function to accept a TimeSpan. 2. Assuming you have done the simplest code possible you would have probably passed in a TimeSpan that returned ‘Good afternoon’ © Thisis fine, do the simplest thing possible , we do however know that the GetMessage function is not complete. 3. Add tests to validate the message are returned correctly, itis valid if you don’t perform as many tests as you know you have tested the GetTimeBasedGreeting, 4, Ifyou have copied my code you will also have noticed that we needed to fix some tests where the GetTimeBasedGreeting returned lowercase values for If you were also a regular TDD. developer you might note that the code had a smell, meaning the code does not look right. afternoon, morning and evening. Go ahead and fix up the test ~_as a developer you have responsibility to make corrections to invalid tests as well as fixing the code. 5. You should now have a GetMessage method looking something like this Figure 13. GetMessage with Time based response. 26 August 2008 v1.0 Page 7 of 27 Beginners Guide to Test Driven Web Part Development public string GetMessage (string message, Timespan timespan) { return GetTimeBasedGreeting (timespan) + ", " + message; Figure 13, GetMessage with Time Based response 6. You will also have a number of unit test for this that look something like Figure 14. Time Based Greeting Tests, you may have added additional tests to check for ‘Good evening; as well. [Test] public void GetMessage_validParameter_ReturnsMessage () { Basic.Welcome welcome = new Basic.Welcome(); string message = "Welcome to our SharePoint site.": Assert -AreBqual ("Good afternoon, " + message, we lcome .GetMessage (message, new TimeSpen(12,0,0)))+ } [test] public void GetMessage_ValidAlternativeParameter_ReturnsMessage () { Basic.Welcome welcome = new Basic.Welcome(); string message = "Welcome to our TOD site."; Assert -AreBqual("Good afternoon, " + message, welcome .GetMessage (message, new Timespen(12, 0, 0))) 3 [test] public void GetMessage_validateTimebasedMessage_ReturnsTimeBasedNes} { Basic.Welcome welcome = new Basic.WelcomeQ); string message = "Welcome to our TDD site."; Assert AreBqual ("Good morning, " + message, welcome .GetMessiage (message, new TimeSpan(6, 0, O))); Figure 14, Time Based Greeting Tests Very quickly we have managed to code the unit tests and system code to perform the core requirements of our web part, We will continue with the web part class. 26 August 2008 v1.0 Page 18 of 27 Beginners Guide to Test Driven Web Part Development Step 7. Creating the web part This white paper is not aimed at teaching you how to develop web parts, there is more than enough good examples of this available, if you want more detailed instructions on creating web parts you should look at the excellent labs available from Microsoft at http://www.microsof ick/SharePointDeveloper/ . ‘om, We are now going to package up our unit tested class into a web part. And you probably expect some gems of information explaining how to do unit testing of web parts. Let's take a step back here and think about what Unit Testing is. | would like to quote Roy Osherove's Unit Testing vs. Integration Testing : The Restaurant Analogy as | think this helps us to understand this, Imagine going to a restaurant with a bunch of your friends. There | are some couples there as well as singles. At the end of the meal, | itis time to pay. Unit testing is like giving a separate bill toeach | couple or single. Each person knows only what they needs to pay | ‘as well as tip, but do not care what anyone else had, or what the total meal amountis. As long as they pay what they need, they | can go home peacefully. ‘everyone having to calculate on their own how much they need to pay. Sometimes everyone things they are good, but in the end the total amount may be too high or too low. There is a lot of, interaction going on to decide who pays for what and who has already p: http://weblogs.asp.net/rosherove/archive/2008/05/31/unit-testing-vs-integration-testing-the- restaurant-analogy.aspx Integration testing is like giving one big check to the group, with ( | | Taking this analogy back to our Web Part the welcome message code we have written above is the same as an individual bill and we have unit tested this. The Web Parts like the full bill, itis where our individual items are brought together and presented, and it can be presented in lots of places with different messages. This functionality was required in our User Story and was the reason we chose to develop the solution as a Web Part; we do not however need to test the Web Part Framework, we accept that this is tested by Microsoft. Our integration testing will demonstrate we have connected our Unit Tested code with the framework and our Unit Tests will test our code works as expected. We will cover the web part code and how to deploy this manually, which will lead us very nicely into the white papers on the other aspects of agile SharePoint development including Integration Testing, Automated solution building and Continuous Integration, 26 August 2008 v1.0 Page 19 of 27 Beginners Guide to Test Driven Web Part Development Creating the Web Part ina few easy steps Let’s get on and create our Web Part; we are not going to use any plug-ins for this like the Visual Studio Extensions for WSS 1. Add a new Project based on Class Library to the existing solution and call UnitTest. Basic. WebParts, as in Figure 15. Add Web Part Project. LI — 2xl [rerrremenas —] Broiect types: = Visual GF ‘Windows Visual Studio installed templates Webs (Gvinows Forms Aeiicston (Pcs tray Smatt Device WPF Aoplstin [WPF Bronzer Aston office Becorsole Aelicaton ennty Frovet Databoce Favndowe Serve (YIP Custom Control ibrary Repertrg (C8) WPF User Contra Lary Winds Forms Contre Library ver Test My Templates wor Weeliowe {Glseach orine Tempates. WSPBldor 9) Other Languages a) Other Proiect Types 3 Test Projects [ Roroiect For creating a G# case ibrery (al) CNET Framenorko5) Mane: [lneteseancwepete SSS Losston: [FiagkesharsPontbev\agiesharePortbevntressSaseSSS~*~S~S~S YB Figure 15. Add Web Part Project 2. Adda reference to System.Web by right clicking on the project and choosing Add Reference. 3, Rename the ClassL.cs file to Welcome.cs and accept the change to the class name in the code. 4. Our Web Parts going to inherit from the ASP.Net Web Part class, Figure 16. Inherit from ASP.Net Web Part shows the code for this. This is the recommended best practice for SharePoint unless you have a specific requirement for the additional features provided by the SharePoint Web Part class, in our simple example we don’t. Finamespace UnitTest.Basic.WebParts ( [public class Welcome : System.Web.UI. WebControls .WebParts.lebPart ql ) aa Figure 16, Inherit from ASP.Net Web Part 26 August 2008 v1.0 Page 20 of 27 Beginners Guide to Test Driven Web Part Development Always start with Hello World! One of the biggest problems with SharePoint development for new and experienced developers alike is the number of things that have to be in place for something to work. This is why | always start my web parts as Hello World web parts and get them on the page, | can then add in my code knowing that I have the configuration in place and any errors are down to my code. Add some simple Hello World code by overriding the RenderContents and add code to write Hello World as in Figure 17. Render Hello World public class Welcome : System.Web.UI.WebControls.WebParts -Webeart i protected override void RenderContents (system .Web.UI Hem lTextteitex weiter) nderContents (writer) ; iter WriteLine ("Hello world"); Figure 17. Render Hello World 6. As this is beginners guide and not aimed at teaching you how to develop web parts lam going to keep this really simple. We need to do the following to deploy our web part a. Copy the DLL to the Web Applications bin directory (no deployment GAC here ©) b. Adda Safe Controls entry for the DLL c. Add the Web Part to our web part gallery like to automate the coping of the Web Part as this allows me to do CTRL+SHIFT+B and have the DLL automatically updated. SharePoint defaults the IIS web site locations to C:\lnetpub\wwwroot\wss\VirtualDirectories\, Under this directory you will find a folder for each of your web applications, you will also see one for your central admin site and maybe your Shared Service Provider if you have created one. We need to copy our Web Part DLL into the bin directory of our web application, in my case this is C:\netpub\wwwroot\wss\VirtualDirectories\agile.21apps.dev\bin ‘Add a Post Build event to your Web Parts project in Visual Studio by right clicking on the project and choosing properties. This will show you a properties page and on the left you will have a Build Events Tab click this and you should see something like Figure 18. Build Events Tab, In here we are going to add a Post-build event, something we want to happen after the project has successfully built, to copy our compiled DLL into the bin discussed above. 26 August 2008 v1.0 Page 21 of 27 Beginners Guide to Test Driven Web Part Development _UnitTest Basic WebParts|/Weleome.es |’ Weleome.cs )Weleome.cs "Start Page Application Configurations [NA J Pstform: [a Pre-bulld event command ine: Buld Buld Events Debug Resources Services Past-buld event command ine: Settings Reference Pathe String I _ ect Post-buld Run the post-build event [on successful bull Code Analysie Figure 18, Build Events Tab 9, Post Build Event code will look something like this cd "S1ProjectDicy™ xcopy $(PargetDir} *.d1L” "C1\Inetpub\wnwroot\wae\Vi rtualDirectories\ [Sitel\bin\" /yy This script makes use of some of the Visual Studio functionality to evaluate the values at runtime, to see what's available and what they evaluate to in your project click the Edit Post- build button and click Macros. In our example we are copying all of the DLLs (*.dll] from the Target Directory (this will be debug/bin in our case) into the SharePoint Sites bin directory, we need to replace the [Site] with the directory in your environment. My post build event looks like this od "5 (ProjeceDiz| " scopy "3 (TargetDir) *.all" ro2\ Inetpub\winecot\w setualDirectories\ agi) apse .dav\bin\" /y 10, Test the post build event now, CTRL+SHIFT+B to rebuild the solution. If the build fails you may have a directory name wrong. Ifit works you should have a copy of the UnitTest-Basic. WebParts in your bin directory. 11. Adding a Safe Controls entry will be done manually for now (we're developers are we ©). SharePoint requires that the DLL is registered as a Safe Control in web.config before it will render it as a web part. Open up the web.config file for your web application and find the SafeControls section, you will see a large number of controls already added including 26 August 2008 V1.0 Page 22 of 27 Beginners Guide to Test Driven Web Part Development Microsoft’s own controls. Add your safe controls entry (it should look the same as below if you used the same Namespaces as me). yebFarts" ‘ypeName-""" Safe-"True" />

You might also like