Testing the Port Scanning Functionality
Explore how to write tests for port scanning functions in Go CLI applications using the Cobra framework. Learn to create reproducible tests simulating open and closed TCP ports on localhost, handle host existence checks, and validate port states to ensure robust network scanning capabilities.
Creating the scanHosts_test.go file
We create a file scanHosts_test.go for the tests. We define the package package scan_test so it only tests the exposed API, as we did with the hosts tests:
Then, we add the import section.
For these tests, we’ll use:
- The
netpackage to create a local TCP server. - The package
strconvto convert strings to integer numbers. - The
testingpackage for the testing function. - The
scanpackage that we’re testing.
The import list
Adding the TestStateString() function
Now, we add our first test function TestStateString() to test the String() method of the state type. We want to ensure it returns open or closed:
Adding the function TestStateString()
For this test, we’re defining an instance of the type scan.PortState. By default,
the ...