Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
132
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Chapter 52

programmer environment having the most marked difference from the other language options sets. Because of this variance in setup, you should review these options carefully to ensure that each option you require has been activated. To aid you in getting this right, the following list explains what each option does when activated.

Figure 52-1

Ask before deleting all breakpoints: You can clear all breakpoints appearing in a particular document or window through the Edit Breakpoints submenu. Because the action cannot be undone, you can activate this option to ask for confirmation before performing it. Interestingly, for Visual Basic programmers this option is not on by default, meaning all breakpoints will be cleared without confirmation.

Break all processes when one process breaks: This option is active by default in all situations and causes all processes in a multi-process project to halt whenever a breakpoint or error is encountered. This enables all processes to be kept in sync, but in some rare situations you may want to allow background or second-tier processes to continue to execute while you debug the module that was paused.

Break when exceptions cross AppDomain or managed/native boundaries: Inactive by default, this option enables you to break when processing exceptions that cross managed code and unmanaged code such as COM applications. You can usually ignore this setting, but it can be handy when debugging applications that use the COM Interop to interface between the two types of programming language.

Enable address-level debugging: Many of the debugging windows, such as Registers and Disassembly, are only appropriate for address-level debugging. While this is useful, in some rare situations it can affect the way your code is executed, particularly in real-time sensitive processing.

Show disassembly if source is not available: When using address-level debugging, you can also include a disassembly of any portion of the application that does not have source code associated with it. By default, this option is turned off, as it can affect performance slightly.

736

Other Debugging Techniques

Enable breakpoint filters: Breakpoint filters can control when breakpoints are activated by setting them for specific threads or processes. This option, active by default, can control whether these filters are active or not.

Enable the exception assistant: Another useful feature discussed previously, the Exception Assistant can be turned off when debugging managed code. When deactivated, the exception dialog window used in previous versions of Visual Studio is used instead when an exception is encountered.

Unwind the call stack on unhandled exceptions: This option enables you to examine the detail found in the call stack even if the current error was not caught by an exception handler.

Enable Just My Code: Any code that is specifically part of your project and not part of the underlying system framework or external to the current application is termed by Visual Studio as My Code. Activating this option enables you to restrict the step-through process of the debugger only to that code considered part of the My Code block. Note that this option only affects debugging of managed code.

Show all members for non-user objects in variables windows: Non-public members of objects in the non-My Code sections can be included in the variables windows. This option is only appropriate for Visual Basic code.

Warn if no user code on launch: On by default for all environmental setups except for Visual Basic, this option displays a dialog warning when no code is found in the My Code section of your application.

Enable property evaluation and other implicit function calls: This option enables you to access properties and function calls in both the QuickWatch dialog window and the variables windows. Without this option active you will need to explicitly call functions.

Call ToString() on objects in variables windows: C# code normally requires explicit

ToString() function calls for any object type to display the string representation of the object. Without this option active, displaying an object in a variable window only displays the type name instead of the actual data contents. You can change this behavior with this option.

Enable source server support: The source server is a way of retrieving otherwise unavailable source code. It requires a special DLL called srcsrv.dll and reads the application’s PDB file to determine the exact version of source files.

Print source server diagnostic messages to the Output window: When using source server support, you can output any diagnostic messages to the Output window by activating this option.

Highlight entire source line for breakpoints and current statement: For statements that break over multiple lines, this option controls how the breakpoints are displayed. With the option on, which is true for Visual Basic environment setups only, the entire source line is highlighted.

Require source files to exactly match the original version: Activating this option forces the debugger to first verify the source code that is to be used to debug against the original source. If they do not match, you will be prompted to locate the original source before the debugging can continue.

737

Chapter 52

Redirect all Output Window text to the Immediate Window: This controls where the debugging output that normally goes to the Output tool window will end up. Activating this option forces the content to be directed to the Immediate window instead. This can be useful when you want to see all of your output in one location, with functions you perform in the Immediate window being displayed in the context of any debugging output that is also displayed.

Show raw structure of objects in variables windows: As discussed in the previous chapters, Visual Studio goes a long way in visualizing the data found in objects into a readable form. However, if you want to view the information as it appears in the original object definition without any view customizing, you can activate this option.

Suppress JIT optimization on module load: By default, when running an application in debug mode, the JIT optimization options are disabled so you can more easily determine the exact source of a particular issue. Deactivating this option enables the JIT compiler to also optimize the code when a module is loaded, in the same way as it does in a non-debug build. You will see the same performance increase as if you were running the project outside the debugging environment, but you may find it more difficult to track down problems. Obviously, this option has no effect on native code.

Warn if no symbols on launch: When debugging native code, you normally use debugging symbols to track down issues. If no symbols are defined, then this option will produce a warning dialog window to let you know that you will not be able to successfully debug the code.

Debug Page in My Project

In addition to the global options you have available to you in Visual Studio 2005, you can also customize the debugging experience further for an individual project. The Debug page (see Figure 52-2) is accessible for managed code languages such as Visual Basic and C# and can be used to control how the project should be started.

Figure 52-2

738

Other Debugging Techniques

By default, Visual Studio assumes that you want to start the project directly, but you can also choose to start an external program that presumably will subsequently call your project into the execution process. Alternatively, you can choose to launch the default web browser on your system with a specific URL, again with the assumption that the URL will ultimately invoke your project.

Often, applications are built with the capability to exhibit different behavior depending on commandline arguments. If your project is of this variety and you need to test the different configurations, the Command Line Arguments textbox can be used to specify which set of arguments are to be included in the execution of the project. You should enter the command-line arguments in exactly the same way you expect the end user to when invoking your application once it has been deployed.

You can override the default directory from which the application should be executed by setting the Working Directory option. This equates to the same setting when you edit a Windows shortcut. In addition, you can also specify a different machine to control the debugging process of the application by activating the Use Remote Machine option. Note that you will need to explicitly specify the remote computer path, as it does not have an associated browse option.

The final section of the Debug page pertains to the different kinds of debugging that will be performed during the execution of your application. By default, the only debugging process active is the debugging of managed code inside the Visual Studio environment, but you can optionally include unmanaged COM code or other native code that falls outside the managed code arena in the debugging process by selecting the Enable Unmanaged Code Debugging option.

Finally, if your application includes SQL Server 2005 databases, then you can debug right into the stored procedures associated with the database by activating the Enable SQL Server Debugging option.

The configuration and platform settings are available only when you have the Show Advanced Build Configurations setting activated. This can be found in the Projects and Solutions General options page and is on by default for all environment configurations except for Visual Basic programmers.

Exception Assistant

The basic usage of the Exception Assistant was discussed in previous chapters, along with some information about how to create your own visualization options to customize its appearance. However, it’s worth recapping the usefulness of this window when debugging, and how to retrieve further information via the Exception Assistant dialog window when it is displayed.

The first thing to note is that the Exception Assistant is available to you in all managed code projects regardless of project type. This means you get the benefit of this feature for web debugging as well as Windows-based application programming. However, if you would prefer the older style exception dialog window that was used in previous versions of Visual Studio, you can deactivate the feature through Visual Studio options (see the “General Options” section earlier in this chapter).

Every exception intercepted by the Exception Assistant has an associated section in the documentation to further explain the issue and what action you can take to fix any problems. This includes more detail about the associated tips that are displayed in the dialog so you can understand what each suggestion means, and additional links to other parts of the documentation if you want to investigate a particular solution further. Figure 52-3 shows a typical documentation page for one of the more commonly encountered errors, NullReferenceException.

739

Chapter 52

Figure 52-3

When dealing with a particular issue reported by the Exception Assistant, sometimes it is difficult to determine which particular action you should take to rectify the problem without additional information. To help you with this, the View Detail link, available for every exception, can be used to access full details for the error.

The View Detail dialog uses a default object visualizer to display the information found in the exception object structure in a readable format (see Figure 52-4).

740

Figure 52-4

Other Debugging Techniques

As you can see, you can navigate right down to the individual property level within the exception object, which enables you to accurately determine what data is included in the issue so you can establish what corrective action you should take.

Debugging Macros

In Chapter 26 you learned how to use macros to automate series of tasks within the Visual Studio IDE. These macros are written in Visual Basic and have an extensive programming model associated with them, including their own IDE for development.

Included with the IDE is a standalone debugging process. As a result, unlike other development tools that simply halt when an error is encountered in macro code, Visual Studio 2005 macros can be fully debugged using an interface very similar to that found in the main IDE.

As Figure 52-5 shows, you have access to a wide array of debugging windows and features, just like in the main Visual Studio 2005 IDE. You can also add manual breakpoints to the macro code, which forces the Visual Studio Macros IDE to open and display the code at the breakpoint when you execute the command from within the main IDE.

Figure 52-5

There are some limitations to macros, unfortunately, and one in particular can impact your understanding of the underlying objects that allow the macro code to act on the Visual Studio environment. Debugging macros only acts on the managed code of the macros themselves, so all native code is

741

Chapter 52

excluded from the debugging session. This includes the COM objects related to the IDE itself, such as the DTE object, which means you cannot look at certain properties of these objects during a debugging session. Instead, you need to use the Immediate window to determine the values.

Debugging Database Stored Procedures

Another incredibly useful feature of the debugging model found in Visual Studio 2005 is the capability to debug stored procedures in SQL Server 2005 databases. You’ll need to first check the Enable SQL Server debugging setting in the Debug page of your project. Once activated, whenever your code encounters a stored procedure, you can debug the procedure code inline with your own code.

You can even include breakpoints within a stored procedure so you can trace through the SQL Server code without halting the application code execution (see Figure 52-6).

Figure 52-6

Summar y

This chapter completes the discussion on debugging your projects and applications, offering details about how you can customize the general experience of your debugging sessions. In addition, Visual Studio 2005 is capable of debugging other areas of your code that previously were excluded from the debugging process, such as stored procedures and macro code, so you have a more cohesive testing experience that includes familiar debugging options regardless of what issue you’re facing.

Armed with the information in this chapter, along with the coverage of unit testing in the next chapter, Visual Studio 2005 will help you address almost every situation you encounter as you create your applications, regardless of the technology you’re using.

742

Unit Testing

Application testing is one of the most time-consuming parts of writing software. The statistics available from research into development teams and how they operate has revealed quite staggering results. Some teams employ a tester for every developer they have. Others maintain that the testing process can be longer than the initial development. This indicates that contrary to the way development tools are oriented, testing is a significant portion of the software development life cycle. This chapter looks at a specific type of automated testing that focuses on testing individual components, or units, of a system.

Visual Studio Team System is the first version of Visual Studio that has a built-in framework for authoring, executing, and reporting on test cases. This chapter focuses on unit tests and adding support to drive the tests from a set of data. Chapter 56 covers the other types of tests that can be created, along with the various testing windows that can be used to manage the test cases and results.

Your First Test Case

Writing test cases is not easily automated, as the test cases have to mirror the functionality of the software being developed. However, at several steps in the process code stubs can be generated by a tool. To illustrate this, start with a relatively straightforward snippet of code to learn how you can go about writing test cases that fully exercise the code. Setting the scene is a Subscription class that has a private property called CurrentStatus, which returns the status of the current subscription as an enumeration value:

Public Class Subscription

Public Enum Status

Temporary

Financial

Unfinancial

Suspended

Chapter 53

End Enum

Private _PaidUpTo As Nullable(Of Date)

Public Property PaidUpTo() As Nullable(Of Date) Get

Return _PaidUpTo End Get

Set(ByVal value As Nullable(Of Date)) _PaidUpTo = value

End Set End Property

Public ReadOnly Property CurrentStatus() As Status

Get

If Not Me.PaidUpTo.HasValue Then Return Status.Temporary

If Me.PaidUpTo.Value > Now Then

Return Status.Financial

Else

If Me.PaidUpTo >= Now.AddMonths(-3) Then

Return Status.Unfinancial

Else

Return Status.Suspended

End If

End If

End Get

End Property

End Class

As you can see from the code snippet, four code paths need to be tested for this property. In the past you would have to manually create a separate SubscriptionTest class, either in the same project or in a new project, into which you would manually write code to instantiate a Subscription object, set initial values, and test the property. The last part would have to be repeated for each of the code paths through this property.

Visual Studio Team System automates the process of creating a new test project, creating the appropriate SubscriptionTest class and writing the code to create the Subscription object. All you have to do is complete the test method. It also provides a runtime engine that is used to run the test case, monitor its progress, and report on any outcome from the test. As such, the only part that remains for you to do is write the code to test the property in question. In fact, Team System generates a code stub that executes the property being tested. However, it does not generate code to ensure that the Subscription object is in the correct initial state; this you must do yourself.

Test cases can be created from the Test menu by selecting the New Test item. This prompts you to select the type of test to create, after which it creates a blank test in which you need to manually write the appropriate test cases. To automate the mundane work of writing the stub code, you need to create the unit test by selecting the Create Unit Tests menu item from the right-click context menu off the main code window. For example, right-clicking within the CurrentStatus property and selecting this menu item brings up the Create Unit Tests dialog displayed in Figure 53-1. This dialog shows all the members of all the classes within the current solution and enables you to select the items for which you want to generate a test stub.

744

Unit Testing

Figure 53-1

If this is the first time you have created a unit test, you will be prompted to create a new test project. Unlike alternatives such as NUnit that allow test classes to reside in the same project as the source code, the testing framework within Visual Studio Team System requires that all test cases reside in a test project. When test cases are created from the dialog shown in Figure 53-1, they are named according to the name of the member and the name of the class to which they belong. For example, the following code is generated when the OK button is selected:

<TestClass()> _

Public Class SubscriptionTest

Private testContextInstance As TestContext Public Property TestContext() As TestContext

Get

Return testContextInstance End Get

Set(ByVal value As TestContext) testContextInstance = Value

End Set End Property

<TestMethod()> _

Public Sub CurrentStatusTest()

Dim target As Subscription = New Subscription

‘TODO: Assign to an appropriate value for the property Dim val As Subscription.Status

Assert.AreEqual(val, target.CurrentStatus, _ “DeveloperNews.Subscription.CurrentStatus was not set correctly.”)

Assert.Inconclusive(“Verify the correctness of this test method.”) End Sub

End Class

745