Reputation: 36287
Lets say I have a someMethod
that takes a String
and int
or any other type as its inputs.
When I want to write my Unit tests for this someMethod
, am I to populate the method with my own given String and Int and then run it through my tests? Wouldn't that make my tests dependent to my input?
And presumably their value (the string and int input) is coming from another function, I should have a separate unit test for that function as well right?
Upvotes: 2
Views: 5602
Reputation: 63252
Functions (or methods) that rely solely on their parameters for input (and not global/instance state) and their return value for output are actually the easiest to test. They're called pure functions. It's becoming increasingly popular to strive to have as much code exist in "pure" functions, because of how easily testable they are.
You give them sample input (from hardcoded values, a mock framework, test database, etc.), and you compare the output with what you expected.
On the other hand, dealing with non-pure functions/methods in tests is much harder. You need to set up an instance's state to a particular precondition, call the method to be tested, then test the instance after mutation. It's a much longer process.
Upvotes: 3
Reputation:
Unit tests are mostly for testing interfaces, you have defined behaviors for your code and you're testing those behaviors. For example, you have a set of code that capitalizes a String
. You would pass in a couple of different sets of text and verify that they work:
Input | Expected Output | Rationale
-------------------------------
test | TEST | all lower
Test | TEST | initial caps
tEst | TEST | middle caps
tesT | TEST | last caps
foo | FOO | checking different string
1foo | 1FOO | mixed string
etc...
Yes, you should make your unit tests comprehensive and try to cover as much code as possible. You can test individual functions but it's more important to test interface of objects, protocols, and important standalone functions. That's why it's called a unit test, you are testing a block or unit of code - not individual pieces.
Upvotes: 1