Write Unit Test with expected Message

From the comments,

The third argument of Test is the list of expected messages, e.g.

Test[1/0, ComplexInfinity, {Power::infy}]

The Mathematica system function VerificationTest is based on Test and has a similar design.


I think it's useful to know all possible forms of expected messages accepted by Test.

It accepts MessageName expression and list of such expressions (as already shown in ilian's answer):

Test[Message[f::argx, f, 2], Null, f::argx]
Test[Message[f::argx, f, 2]; Message[g::argr, g, 3], Null, {f::argx, g::argr}]

Test also accepts Message expression and list of Message expressions. This form tests message names and arguments, but it automatically wraps message arguments with HoldForm, so it can be used only to test messages that are emitted with HoldForm-wrapped arguments.

Test[Message[f::argx, HoldForm@f, HoldForm@2], Null, Message[f::argx, f, 2]]
Test[
    Message[f::argx, HoldForm@f, HoldForm@2];
    Message[g::argr, HoldForm@g, HoldForm@3]
    ,
    Null
    ,
    {Message[f::argx, f, 2], Message[g::argr, g, 3]}
]

Third, most versatile, form accepted by Test, is list of Message expressions wrapped with HoldForm. In contrast to previous form, it does not wrap arguments with anything, so it can be used to test arbitrary arguments.

Test[Message[f::argx, f, 2], Null, {HoldForm@Message[f::argx, f, 2]}]

Important fact is that all above forms of expected messages are used as patterns, against which actual messages are matched. So arbitrary patterns can be used:

Test[Message[f::argx, f, 2]; Message[g::argr, g, 3], Null, {(f | g)::argx, g::argr}]
Test[Message[f::argx, HoldForm@f, HoldForm@2], Null, Message[f::argx, f, _Integer?Positive]]
Test[Message[f::argx, f, 2], Null, {HoldForm@Message[f::argx, f | g, _Integer]}]

It also needs to be taken into account when actual message contains a pattern itself, then pattern inside expected message needs to be wrapped with Verbatim:

Test[Message[f::fake, _String], Null, {HoldForm@Message[f::fake, Verbatim@_String]}]