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.