I have parametrized test with 2 variants:

  • NULL value


  • any NOT NULL value

From this value is depends one assert:

  • In case NULL it should be checked if object has field1 with value1
  • In case NOT NULL it should be checked if object has field2 with value2

As I mentioned (see xUnit Tests Patterns ) using conditional statements in assert is anti-pattern.

How can I solve this problem properly?

I am trying at the moment to apply Guard assertion pattern:

  • if-assertion is splitted into 2 assertions
  • At the beginning there is test parameter check (NULL/NOT NULL) with guard assertion:

    it('case describing conditionalParamter=NOT NULL'):
        expect(conditionalParamter, 'to be a', 'string') // Guard assertion which can FAIL test. Is it OK? Can I simply **SKIP** assertion WITHOUT test failing 
        expect(myStub.args, 'to satisfy', [[ nonConditionalParamter,  ExpressionWhichUsesNonNullConditionalParamterValue ]])
    it('case describing conditionalParamter= NULL')
        expect(conditionalParamter, 'to be falsy') // Guard assertion. The same issue
        expect(myStub.args, 'to satisfy', [[ nonConditionalParamter,  ExpressionForNullConditionalParamterValue ]])

But in this case we have 2 failed assertions. Is it appropriate solution?

Is there better ways to solve problem?

  • I have no idea how this particular unit testing framework works, but it sounds like you're saying it has a way of saying "use any non-null value for test 1 and null for test 2" and yet it does not have a way of saying "assert that this parameter was null (or not null)", which sounds massively broken to me. Is that the issue here?
    – Ixrec
    Commented Mar 8, 2016 at 10:59

1 Answer 1


Not sure what test framework you're using. But, this is what it might look like in RSpec (Ruby):

Method under test:

class Foo
  def bar(required_param, conditional_param = nil)
    return 'abc' if conditional_param.nil?


describe Foo do
  subject(:foo) { described_class.new }

  describe '#bar' do
    subject(:bar) { foo.bar(required_param, conditional_param) }

    let(:required_param) { 'required_param' }

    context 'when conditional_param is nil (not present)' do
      let(:conditional_param) { nil }

      it 'returns abc' do
        expect(bar).to eq('abc')

    context 'when conditional_param is not nil' do
      let(:conditional_param) { true }

      it 'returns 123' do
        expect(bar).to eq('123')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.