1

Is it possible to write effective unit tests for unstructured code?

I was reading through the various answers to this question. It explains the implications of unit testing procedural and OOP code, but there is very little mention about unstructured code.

In my personal experience, I've only written unit tests for functions and class methods. I imagine that it would be difficult indeed to test unstructured code, but I'm also curious to know if it's possible, and what the best practices are for unit testing such code.

  • You don't need any structure at all to write unit tests for a single method, especially a pure one (having no side effects). – Robert Harvey Nov 06 '15 at 01:41
  • I understand unit testing methods and functions, but I'm asking about how to test code that is not organized by functions or classes. Ie, code that is many lines long and entirely written in the global scope. – Dirty Penguin Nov 06 '15 at 03:11
  • recommended reading: **[Why is “Is it possible to…” a poorly worded question?](http://meta.programmers.stackexchange.com/a/7274/31260)** – gnat Nov 06 '15 at 04:41

2 Answers2

4

No. Unless you want to seriously twist the meaning of the term "unit testing" in such a way that it essentially becomes synonymous with "system testing", unit testing a system that has no individual units to test, is meaningless.

You can of course do system testing. If the code performs multiple functionalities, you can do functional testing. If the code integrates with other code, you can do integration testing. If you have some acceptance criteria for the code, you can do acceptance testing. You can do performance testing.

But you can't do unit testing, because unit testing tests individual independent units in isolation, and there are no individual independent units in unstructured code (that's pretty much what "unstructured" means).

Jörg W Mittag
  • 101,921
  • 24
  • 218
  • 318
1

You are basically talking about one very big unit. Normally, you would write lots of small unit tests for small units, but in this case it will likely be a lot of elaborate tests for one big unit.

At my work, we have the same kind of problem. In some of our products we use SOUP (Software of Unknown Provenance), which we have to 'unit test' to comply with rules and regulations pertaining to our products.

SOUP can be a library, e.g. a Bluetooth stack, or a an execution framework, e.g. QP/C. We write tests that execute the API or write test applications that integrate the SOUP and test its (internal) functions.

One important function of these tests is to detect regression or undesirable changes when the SOUP is updated. But most of the time, these tests are used to verify that the SOUP does what it is expected to do and that there are no nasty surprises or corner-cases.

Developing 'unit' tests for a piece of unstructured software is also very useful if you want to restructure it or replace it.

NZD
  • 266
  • 1
  • 8