0

I'm doing some TDD using JUnit4, Mockito, and Hamcrest. My current test looks like this:

FeatureFilter featureFilter = FeatureFilter
    .describeFeature()
    .addFeatureRef("myNewFeature",
        thatIsAvailable()
            .atEndpoint("/resourceWithFeature"))
    .andDisable();

assertThat(featureFilter.isDisabledFor("/resourceWithFeature", null, "myNewFeature"), is(true));
assertThat(featureFilter.isDisabledFor("/irrelevant", null, "myNewFeature"), is(false));
assertThat(featureFilter.isDisabledFor("/resourceWithFeature", null, "self"), is(false));

The second argument to featureFilter.isDisabledFor should be a username (String), and what I want the test to communicate is that the username is irrelevant in this case. If I were in the context of a test double I could use a Matcher such as any(String.class), but that's not an option here.

How would you, as a developer, communicate this assertion's intent?

  • 2
    To get things moving I added a `public static final String` called `ANY_USER` but I'm not too jazzed about that solution. – R. Michael Rogers May 03 '15 at 02:31
  • 1
    I think your solution is ok - but it's just a hint to the reader/maintainer. If the irrelevance is really part of the specification of this object, you may try out Junit theories. Theories execute a certain test with multiple data points (e.g. users) and fail if one of them does not satisfy the assertions. – CoronA May 03 '15 at 05:27
  • @CoronA - I had never heard of Theories before, but holy crap are they awesome. I rewrote my tests using them and the difference is amazing. Take a look at [this gist](https://gist.github.com/mike-rogers/2a238278a67e51627970). You should answer so I can give you fake internet points. ;-) – R. Michael Rogers May 03 '15 at 14:27

1 Answers1

1

There is a feature called JUnit Theories. @Test and Theory have a different focus on testing:

  • a Test is input-output-related (on some input, expect some output)
  • a Theory is algorithm related, i.e. it makes assertions on the behaviour of the called function, accepting a large set of input parameters (being representative for all possible input parameters. Often the output of such a theory is not fixed but computed.

Applied to your problem:

  • Since an unused parameter does not affect the output, a test cannot assert this behavior.
  • A theory with different data points can assert at least that the behavior of being user-independent holds for all user data points.
CoronA
  • 7,717
  • 2
  • 26
  • 53