Testing protocols?

Is there any way to test a Protocol? For example, I’ve got a protocol that handles JSON encoding of Mongo BSON.Timestamps:

defimpl Jason.Encoder, for: BSON.Timestamp do
  def encode(%BSON.Timestamp{value: timestamp}, _opts) do
    Jason.Encode.value(timestamp, nil, nil)
  end
end

How can you assert ExUnit tests against that?

Ah, nevermind: it seems you just have to call it indirectly, e.g.

    test "ok for BSON.Timestamp conversion" do
      assert {:ok, "1576273999"} = Jason.encode(%BSON.Timestamp{value: 1_576_273_999, ordinal: 919})
    end

Besides to just call the wrapper as you already did, you can also use this trick:

Given a protocol p and its implementation for i, it compiles into the module Module.concat(p, i).

So in your example, Jason.Encoder.BSON.Timestamp.

1 Like