Question

Can anybody recommend a pattern for unit-testing code within a Mathematica notebook? I am familiar with the unit testing infrastructure in Wolfram Workbench, but I would also like to have a good approach that can be used within simple notebooks in the regular GUI.

I've been using a simple "Expect" function as demonstrated below. But the problem is that I must then re-evaluate the notebook and scan through it visually for failures. What would be a good way to create a list of tests, or alternately to scan through the notebook and generate such a list, so they can all be evaluated in a single call?

In[8]:= Expect[ description_, val_, expr_ ] := 
If[
    val == expr,
    "ok",
    StringJoin[ "ERROR: GOT UNEXPECTED VALUE ", ToString[expr], 
    " INSTEAD OF ", ToString[val] ]
]

In[9]:= Expect[ "test passes", True, True ]
Out[9]= "ok"

In[10]:= Expect[ "test fails", True, False ]
Out[10]= "ERROR: GOT UNEXPECTED VALUE False INSTEAD OF True"
Was it helpful?

Solution

So, what I do is simply making a list of statements that evaluate to true or false, depending on whether the tests pass or not. Since there aren't hundreds of tests but usually less than 10, this works fine for me.

If I were to do it more outomatically, I'd probably use Throw, for it simplifies debugging.

So, I'd do:

Expect[ description_, val_, expr_ ] := 
If[
    val != expr,
    Throw[
        StringJoin[ "GOT UNEXPECTED VALUE ", ToString[expr], 
        " INSTEAD OF ", ToString[val] ]
        , "assertion exception"
    ]
]

OTHER TIPS

I decided to roll my own mini-testing framework in a Mathematica notebook. In addition to running unit tests, it supports setup and teardown functionality.

https://github.com/chrisoei/Mathematica-Test-Runner

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top