TDD is supposed to have 100% code coverage. Does this mean one is supposed to write tests for property getter and setters, and other methods that contain no real logic, such as dealing with external API functionality?
Example 1:
Below is one example method (which happens to also be the example in this other SO question which deals with how best to test it, if we are going to test it). This method doesn’t do much. It’s a facade of the System.ServiceProcess.ServiceController functionality of stopping a service. Currently this code was not being written using TDD, but if it was, would it be something that one should test? There is very little logic here. The test in and of itself wouldn’t be that helpful.
FYI: If you’d like to answer on how best to test it (IoC & Adapter Pattern vs. Detouring) please see this other SO question.
Public Function StopService(ByVal serviceName As String, ByVal timeoutMilliseconds As Double) As Boolean Implements IWindowsServicesService.StopService
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
Return False
Catch ex As TimeoutException
Return False
End Try
End Function
Example 2:
In case one argues that the code still has some logic, and therefore it needs to be tested when doing TDD, then what about the following code that has no logic:
Public Function GetProcess(ByVal serviceName As String) As Process
Dim managementObject As New ManagementObject(String.Format("Win32_service.Name='{0}'", serviceName))
Dim processID As Integer = CType(managementObject.GetPropertyValue("ProcessID"), Integer)
Dim process As Process = process.GetProcessById(processID)
Return process
End Function
TDD is not supposed to have 100% code coverage. TDD tends to have very high code coverage, as compared to other methodologies. If you don’t write a line of code without a failing test, if you follow that strictly, then yes, you’ll get to 100% coverage. But most of us don’t follow that strictly, and perfect code coverage is not the objective of TDD. High code coverage is a nice side effect of Test-Driven Development, but it is not the point.
Most of us don’t test-drive simple getters and setters specifically as part of the TDD process. But we’re not creating that field which needs the getter and setter until we have a need for it – where “need” is defined as a failing test. So the getter & setter will be tested as a matter of course, because they’re created as needed by methods we are test driving.
Both of your examples have enough logic in them to be worthy of tests; I would test-drive both of them.