Custom Assertions

Custom Assertions - How To

Sometimes you need complex and/or repetitive assertions. This can put a damper on any TDD effort. So, we provide you an easy way to add custom assertions to your tests without having to change the mxunit core.

The steps for creating your custom assertion are as follows:

  1. Write a test for your assertion
  2. Write the assertion
  3. Decide how you want to load it: Always or only on selected tests.

Assertion Rules:

  1. Your assertion will need to throw mxunit.exception.AssertionFailedError or use an existing assertion that throws this exception.
  2. If you want to have optional first or last parameter message, you will need to call normalizeArguments(arguments) in your code.

Custom Assertion Example: Say you need to frequently validate email addresses. You can do this with a pretty regular expression such as this :


The code for this might look like:

This is fine, but you could save yourself some typing and some Ctrl+C/Ctrl+V errors. How about something that looks like this instead?

Much better! And this has the added bonus of not having to find a replace hundreds of complex regular expressions in your code; you would just do that in one place.
Here's how:

1. Write a test for your assertion:

The above fails because we do not yet have ValidEmailAssertion written. Notethe addAssertDecorator("mxunit.framework.ext.ValidEmailAssertion") statement. This tells the MXUnit framework to load your assertion at runtime.

2. Write the assertion

You could also leverage existing assertions and write the following instead:

Note the arguments = normalizeArguments(arguments) statement. This allows for the flexibility if you want to be able to pass the message parameter first or last.

Ok. Now when we run our test, we're in the green. Our new assertion works as expected. Wahoo!

3. Decide how you want to load the new code. The options are for each test or forall tests. You've already seen how to load custom assertions in your code. This can also be done in setUp().

What if you want your new assertion to always be available? Edit the mxunit-config.xml file located in {mxunit install}/mxunit/framework/ Add the following line :

This tells MXUnit to automatically load the custom assertion mxunit.framework.ext.ValidEmailAssertion when it starts and makes assertValidEmail(...) method available to all tests. Note that you can put as many public methods in a custom assertion component as you wish.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Dec 02, 2010

    Anonymous says:

    Looks like each of the functions in your code examples has been pasted in twice,...

    Looks like each of the functions in your code examples has been pasted in twice, although with the first ones having all spaces stripped out.

  2. Dec 02, 2010

    bill shelton says:

    thanks. should be fixed now.

    thanks. should be fixed now.