How to make this unit test independent?

One of unit test best practices is to make each test independent to all the others. Lets say I want to test add() method of a BoundedPriorityBlockingQueue custom class:

public void testAdd() {
    BoundedPriorityBlockingQueue q = BoundedPriorityBlockingQueue();
    q.add(1);
    assertEquals(1, q.size());
}

as you can see currently testAdd uses size() method so it depends on it but I dont want testAdd() to fail when size() is broken. What is the best practice in this situation?

Jon Skeet
people
quotationmark

What is the best practice in this situation?

Just suck it up, bearing in mind that tests are meant to serve you, not the other way round.

Will your tests break if something goes horribly wrong? Yes.

Will it be clear where the problem is? Probably, given that anything using size will fail.

Is this test driving you towards a less testable design? No.

Is this the simplest approach to testing add, which is robust in the face of changing implementation details? Probably. (I'd test that you can get the value out again, mind you.)

Yes, it's sort of testing two parts of the same class - but I really don't think that's a problem. I see a lot of dogma around testing ("only ever test the public API, always use AAA" etc) - in my experience you should temper that dogmatism with a healthy dose of pragmatism.

people

See more on this question at Stackoverflow