我如何testing函数是否返回成功创build的对象?

首先,CreateApp()调用NewAppSheet()。

其次,NewAppSheet()返回一个对象。

第三,CreateApp()testing对象创build是否成功。

我经常遇到这种情况。 这种情况的一个好的做法是什么? 在这种情况下的细微差别是什么(例如:如果对象从来没有成功创build,或者只是指向什么都没有关系)?

下面的代码是我最好的尝试在优雅。 不幸的是,CreateApp()中的Else不会发生,所以我的testing不起作用。

Sub CreateApp() Dim wks As Excel.Worksheet = NewAppSheet() If Not wks Is Nothing Then WriteAppText(wks) Else MessageBox.Show("This never happens") End If End Sub Function NewAppSheet() As Excel.Worksheet Dim sMessage As String = "Message" Dim sTitle As String = "Title" Dim sDefaultValue As String = "" Dim sValue As String Dim wks As Excel.Worksheet ' Display message, title, and default value sValue = InputBox(sMessage, sTitle, sDefaultValue) wks = CType(AddinModule.CurrentInstance, TimeTracker.AddinModule).ExcelApp.ActiveWorkbook.Worksheets.Add() Try wks.Name = sValue Catch wks.Delete() MessageBox.Show("A worksheet with that name already exists. Please type a different name next time.") End Try NewAppSheet = wks End Function 

我知道我可以创build一个名为bSuccessful的variables,并在我的testing中使用它。 但是我认为一定有更好的程序员使用的更好的做法,所以我问你们呢?

你永远不会碰到你的Else语句,因为NewAppSheet永远不会返回Nothing

 Try wks.Name = sValue Catch ' This will delete the sheet. ' It will NOT set wks to Nothing. wks.Delete() MessageBox.Show("A worksheet with that name already exists. Please type a different name next time.") ' Explicitly set wks object to nothing. wks = Nothing End Try ' Use Return instead of assigning to the function name. Return wks 

正如在上面的代码片段中指出的那样,在VB.NET函数中使用Return通常是一种好的做法,而不是将值NewAppSheet = wks函数名称(例如NewAppSheet = wks ),这是在VBA中完成的。

既然你也在征求反馈意见:程序上,你的代码和方法对我来说很好。 代码的意图很清楚,我发现很容易遵循。

只要NewAppSheet从Catch块返回Nothing。

  Try wks.Name = sValue Catch wks.Delete() MessageBox.Show("A worksheet with that name already exists. Please type a different name next time.") Return Nothing End Try