Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test the function behavior in unit test?

If a function just calls another function or performs actions. How do I test it? Currently, I enforce all the functions should return a value so that I could assert the function return values. However, I think this approach mass up the API because in the production code. I don't need those functions to return value. Any good solutions?

I think mock object might be a possible solution. I want to know when should I use assert and when should I use mock objects? Is there any general guide line?

Thank you

like image 312
LNK2019 Avatar asked Feb 15 '26 13:02

LNK2019


1 Answers

Let's use BufferedStream.Flush() as an example method that doesn't return anything; how would we test this method if we had written it ourselves?

There is always some observable effect, otherwise the method would not exist. So the answer can be to test for the effect:

[Test]
public void FlushWritesToUnderlyingStream()
{
   var memory = new byte[10];
   var memoryStream = new MemoryStream(memory);
   var buffered = new BufferedStream(memoryStream);

   buffered.Write(0xFF);
   Assert.AreEqual(0x00, memory[0]); // not yet flushed, memory unchanged
   buffered.Flush();
   Assert.AreEqual(0xFF, memory[0]); // now it has changed
}

The trick is to structure your code so that these effects aren't too hard to observe in a test:

  • explicitly pass collaborator objects, just like how the memoryStream is passed to the BufferedStream in the constructor. This is called dependency injection.
  • program against an interface, just like how BufferedStream is programmed against the Stream interface. This enables you to pass simpler, test-friendly implementations (like MemoryStream in this case) or use a mocking framework (like MoQ or RhinoMocks), which is all great for unit testing.
like image 156
Wim Coenen Avatar answered Feb 17 '26 02:02

Wim Coenen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!