Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve an in memory datastructure to later use it in a Unit test

In my code, I am occasionally passed various byte arrays and such. Also, they may be managed objects. I would like to preserve those memory structures so that I can write test cases against the concrete examples.

My standard approach is to hit the breakpoint, use the debugger to find the various values and then either new them up or embed a file or something in the unit test assembly as a resource. Sometimes, this involves writing my own abstraction of the component interaction to make my code depending on something that can be new'ed up.

Is there an easier way? I cannot imagine that this is something new. Let's say that you are given a fire central unit to communicate with. You play around with it to make it produce its datagrams, which you want to create for your unit tests. Also, when you encounter a bug due to some undocumented way that the fire central is composing its composite messages, you want to record and preserve those examples.

Ideally, I would like to be able to record all interaction to my code and then pick and choose various playback scenarios. But just getting the various datagram examples in-memory from the debugger and put it back into a unit test would help me a lot.

Any suggestions?

like image 860
Tormod Avatar asked Sep 29 '09 07:09

Tormod


People also ask

Should I use in memory database for testing?

While some users use the in-memory database for testing, this is generally discouraged; the SQLite provider in in-memory mode is a more appropriate test replacement for relational databases.

Does TestInitialize run for each test?

TestInitialize and TestCleanup are ran before and after each test, this is to ensure that no tests are coupled. If you want to run methods before and after ALL tests, decorate relevant methods with the ClassInitialize and ClassCleanup attributes.


1 Answers

Try with binary serialization.

The above is specifically for the part where you want to save/load the info or some objects holding info that you use to test the interaction with that external system. I prefer to call those tests focused integration tests, to better capture the difference of focus from the unit tests of the rest of your code with other logic you may have.

Try to separate the code that does the specific integration with the external system from the rest of the code in your system. I suggest to put it behind an interface, that you can replace/mock when creating your unit tests for the rest of the system. This way you can have specifically crafted scenarios that test several aspects/logic of your code without hitting the external system - which also means you can run lots of them in seconds.

like image 127
eglasius Avatar answered Nov 01 '22 13:11

eglasius