Unit test a function
I got a very intersting question while writing a unit test.
Can I test a function while using the function in the test code?
For example,
If I have a List<int>
class which has a function called Add()
.
I want to test a target list object with two int already inside: 1 and 2. Now I add the third number: 3, and want to assert the number is successfully added. So I wrote:
public void TestMethod()
{
//initialize
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
//do operation
list.Add(3);
Assert.IsTrue(list.Contains(3));
}
However, the above test case, which is trying to test the开发者_运维问答 target function: Add(), already uses Add() to initialize. I am thinking this corelationship may result in some problem under some conditions, generally speaking...
Is there any test thoery saying that we cannot do this?
Thanks!
Functions may require more than one test. In this case, you would have a function that tested only a single Add()
, and then the one you have above. As long as both pass, you can be (reasonably) confident that your results are solid. If the first test fails, though, then the result of the second test should probably be ignored.
Ideally, though, you'd have access to the internal state of what you were testing, and could therefore provide a different way of setting intial conditions that didn't involve calling the function under test.
In a case like this it's better to make the test more comprehensive. I might do this instead:
public void TestMethod()
{
//initialize
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
// Test setup
Assert.IsTrue(List.Count == 2);
Assert.IsTrue(List[0] == 1);
Assert.IsTrue(List[1] == 2);
//do operation
list.Add(3);
Assert.IsTrue(List.Count == 3);
Assert.IsTrue(List[0] == 1);
Assert.IsTrue(List[1] == 2);
Assert.IsTrue(List[2] == 3);
}
Nothing stops you from doing it, however I do not see value in doing so in this particular example.
There are other scenarios, where it could be valid, e.g. where you want to test specific behaviour:
1) Your 3rd call is going to affect the state of object bit differently from the previous ones, based on the value of the parameter being passed.
2) You are expecting some special behaviour when using the same method third time, such as 3 invalid login attempts.
I think it is not uncommon to write a test method like the one in your example. What matters is the way we look at it.
If our intention for TestMethod() was to test Add(), we are not supposed to use Add() to establish the precondition in the test.
If our intention for TestMethod() was to test the interaction/sequence of Add() and Contain(), it should be OK.
精彩评论