How to write unit tests for your DAML code

Mod note: As of SDK 1.5.0 Scenarios have been superseded by the more powerful Daml Script. We now recommend using that for all purposes. For more information, and to learn how to use Script please check out @Andreas’ post on our blog.

I spent some time recently with reverse engineering some advanced reference applications written by DA team members, available both on the DAML Marketplace and in the DA Github site.

I have learned a lot from this exercise and got a lot of inspiration for my own projects.

One very useful trick I have found is a method for writing unit tests for your DAM code.

I recommend checking it out to anybody, I use it every day since I have discovered it.

The approach is described by @georg in the README of the Shop reference application here (Github link).

The essence of the approach is that you define three scenarios and test if they fit together:

  1. A “given” scenario, which describes the test setup, which is usually the same for all the test cases.
  2. A “when” scenario which describes the test action, that is the input of a specific test case.
  3. A “then” scenario which describes the test condition, that is the expected outcome of the test case.

The general pattern is the following, you can check out the details on the link inserted above:

data Test a b = Test with
  given : Scenario a
  when : a -> Scenario b
  then_ : a -> b -> Scenario Bool

...

gwt = scenario do
  let correct_iou_amount = Test with
      given = given_fixture
      when = when_action
      then_ = then_condition
  run correct_iou_amount

If the gwt (shorthand for “given - when - then”) scenario doesn’t report any errors, you can rest assured your code is correct.

And Georg says that you can also run the test with the daml CLI like this:

daml run damlc -- test daml/ApprovalChain.daml

(which I didn’t try yet, because I found enough that the test file doesn’t report any errors.)

8 Likes

Great short post @gyorgybalazsi!

1 Like

This is pretty smart! I love that you can easily re-use set-up and assertions across tests.

Can you simply write run Test with …, or does that not compile? Perhaps run $ Test with …?

1 Like

Will try, so far I found enough of a test that DAML studio doesn`t complain about the code and prints the scenario results

1 Like

A post was split to a new topic: Importing Daml Contracts in Daml Studio