I’m writing a data structure in C# (a priority queue using a fibonacci heap) and I’m trying to use it as a learning experience for TDD which I’m quite new to.
I understand that each test should only test one piece of the class so that a failure in one unit doesn’t confuse me with multiple test failures, but I’m not sure how to do this when the state of the data structure is important for a test.
For example,
private PriorityQueue<int> queue; [SetUp] public void Initialize() { this.queue = new PriorityQueue<int>(); } [Test] public void PeekShouldReturnMinimumItem() { this.queue.Enqueue(2); this.queue.Enqueue(1); Assert.That(this.queue.Peek(), Is.EqualTo(1)); }
This test would break if either Enqueue or Peek broke.
I was thinking that I could somehow have the test manually set up the underlying data structure’s heap, but I’m not sure how to do that without exposing the implementation to the world.
Is there a better way to do this? Is relying on other parts ok?
I have a SetUp in place, just left it out for simplicity.
Add a private accessor for the class to your test project. Use the accessor to set up the private properties of the class in some known way instead of using the classes methods to do so.
You also need to use
SetUpandTearDownmethods on your test class to perform any initializations needed between tests. I would actually prefer recreating the queue in each test rather than reusing it between tests to reduce coupling between test cases.