请考虑以下停止服务的方法:
Public Function StopService(ByVal serviceName As String, ByVal timeoutMilliseconds As Double) As Boolean
Try
Dim service As New ServiceController(serviceName)
Dim timeout As TimeSpan = TimeSpan.FromMilliseconds(timeoutMilliseconds)
service.[Stop]()
If timeoutMilliseconds <= 0 Then
service.WaitForStatus(ServiceControllerStatus.Stopped)
Else
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout)
End If
Return service.Status = ServiceControllerStatus.Stopped
Catch ex As Win32Exception
'error occured when accessing a system API'
Return False
Catch ex As TimeoutException
Return False
End Try
End Function
Run Code Online (Sandbox Code Playgroud)
为了对单元测试方法我基本上有两个选择:
ServiceController我需要的类的方法包装到我可以控制的接口中.然后可以将此接口注入服务类(也称为控制反转).这样我就可以使用松散耦合的代码,并可以使用传统的模拟框架进行测试.ServiceController以返回预设结果以进行测试.我同意对于使用"传统"单元测试方法的域模型代码最有意义,因为这会导致设计最容易维护.但是,对于处理与Windows API相关的东西(文件系统,服务等)的.net实现的代码,通过额外的工作获得"传统的"可测试代码是否真的有优势?
我很难看到将Microsoft Moles用于诸如ServiceController(或File对象)之类的东西的缺点.在这种情况下,我真的没有看到采用传统方法的任何优势.我错过了什么吗?