TNG / JGiven

Behavior-Driven Development in plain Java
http://jgiven.org
Apache License 2.0
439 stars 98 forks source link

Allow for defining global formatters for certain types #113

Closed janschaefer closed 9 years ago

janschaefer commented 9 years ago

It should be possible in JGiven to globally register formatters for certain types, so that it is not necessary to use an explicit formatter for each parameter usage.

nikowitt commented 9 years ago

Could you please provide an example for that? Currently, my formatters all implement ArgumentFormatter, but not Formatter. Is there a way to also define the ArgumentFormatters as default?

janschaefer commented 9 years ago

Yes. ArgumentFormatter makes no sense in this case as you cannot give additional arguments to the formatter. However, you could, for example, annotate the parameter with additional annotations and evaluate these. Simple example:

    static class FooParamFormatter implements Formatter<FooParam> {
        @Override
        public String format( FooParam argumentToFormat, Annotation... annotations ) {
            return "foo bar";
        }
    }

    public static class TestConfiguration extends AbstractJGivenConfiguration {
        @Override
        public void configure() {
            setFormatter( FooParam.class, new FooParamFormatter() );
        }
    }
nikowitt commented 9 years ago

OK, so in order to avoid dupe formatting logic for default formatters that don't rely on anything else, my current ArgumentFormatters should also implement Formatter, so I can provide a private common formatter method.

janschaefer commented 9 years ago

Yes.

nikowitt commented 9 years ago

OK, something I just discovered: I expected the default formatters to also format all subclasses of a given class. For instance, I want to provide a default enum formatter, so I provided

    @Override
    public void configure() {
        Class clazz = Enum.class;
    setFormatter(clazz, new EnumFormatter());
    }

(I hate this kind of generic handling!)

But here, I need to provide all concrete enum implementations which is not a very good idea.

janschaefer commented 9 years ago

Yes you are actually right. I haven't thought about that. I created a ticket for that (#137)

janschaefer commented 9 years ago

I have implemented the feature. It turned out to be more difficult than expected. You can test it now with 0.9.1-SNAPSHOT.