GithubHelp home page GithubHelp logo

assertj / assertj-assertions-generator Goto Github PK

View Code? Open in Web Editor NEW
58.0 9.0 42.0 1.16 MB

Custom assertions generator

Home Page: http://joel-costigliola.github.io/assertj/assertj-assertions-generator.html

License: Apache License 2.0

Shell 1.05% Java 98.26% Batchfile 0.69%

assertj-assertions-generator's Introduction

AssertJ - Assertions Generator

CI Maven Central

Overview

The Assertions Generator can create specific assertions for your classes. It comes with :

Let's say you have a Player class with name and team properties. The generator will create a PlayerAssert assertions class with hasName and hasTeam assertions. This allows you to write :

assertThat(mvp).hasName("Lebron James").hasTeam("Miami Heat");

Documentation

Please have a look at the complete documentation in the assertions generator section, including a quickstart guide.

assertj-assertions-generator's People

Contributors

alexbischof avatar alextrotsenko avatar bigmichi1 avatar bnorm avatar dependabot[bot] avatar ebramirez avatar eroshenkoam avatar fduminy avatar flaw avatar ghostd avatar glhez avatar joel-costigliola avatar jstrachan avatar miguelbasire avatar mostr avatar mstachniuk avatar nava2 avatar pascalschumacher avatar remibantos avatar sullis avatar twillouer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

assertj-assertions-generator's Issues

Generator appears to skip some classes in jars

Hopefully reproducible with the following:

> wget -O assertj-assertions-generator-2.0.0-unix.zip https://search.maven.org/remotecontent?filepath=org/assertj/assertj-assertions-generator/2.0.0/assertj-assertions-generator-2.0.0-unix.zip
> unzip assertj-assertions-generator-2.0.0-unix.zip
> cd assertion-generator/
assertion-generator> mkdir tmp
assertion-generator> cd tmp
tmp> wget https://jitpack.io/com/github/ga4gh/schemas/d6cc80d/schemas-d6cc80d.jar
tmp> wget http://central.maven.org/maven2/com/google/protobuf/protobuf-java/3.0.0-beta-2/protobuf-java-3.0.0-beta-2.jar
tmp> cd ..
assertion-generator> java -cp "tmp/*:lib/*" org.assertj.assertions.generator.cli.AssertionGeneratorLauncher ga4gh
assertion-generator> find ga4gh/ -type f -name "*.java" | wc -l
9

So 9 files have been generated.

assertion-generator> rm -rf ga4gh
assertion-generator> cd tmp
tmp> unzip schemas-d6cc80d.jar
tmp> cd ..
assertion-generator> java -cp "tmp:tmp/*:lib/*" org.assertj.assertions.generator.cli.AssertionGeneratorLauncher ga4gh
assertion-generator> find ga4gh/ -type f -name "*.java" | wc -l
143

Now 143 files have been generated, which is more what I was expecting.

Is this something really odd with what I'm doing? This looks to me like a bug in how the generator locates classes to generate for.

Support Java 8 Optional Feature

Is it possible to support Java 8 Optional feature for the generator?

Sample model class:

public class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public Optional<String> getName() {
        return name == null ? Optional.empty() : Optional.of(name);
    }
}

Generated assertion class:

public class PersonAssert extends AbstractAssert<PersonAssert, Person> {

  public PersonAssert hasName(java.util.Optional name) {
  }
}

Suggested assert class:

public class PersonAssert extends AbstractAssert<PersonAssert, Person> {

 // Generator might lookup generic type of the Optional and generate the method without Optional parameter
  public PersonAssert hasName(String name) {
  }

  public PersonAssert hasName(java.util.Optional name) {
  }
}

generated assertion should use null safe equals

NPE in the following generated code if actual.getUseCase() returns null.

 public ActorAssert hasUseCase(UseCase useCase)
    {
        // check that actual Actor we want to make assertions on is not null.
        isNotNull();

        // we overrides the default error message with a more explicit one
        String errorMessage = "\nExpected use case of:\n  <%s>\nto be:\n  <%s>\n but was:\n  <%s>";

        // check
        if (!actual.getUseCase().equals(useCase))
        {
            failWithMessage(errorMessage, actual, useCase, actual.getUseCase());
        }

        // return the current assertion for method chaining
        return this;
    }

Generator produces identical assertion methods when class has field/property clash

Suppose that you have a class with a public field called data and a public method called getData(). At present the generator will generate an assertion method hasData(...) for both, which at best is confusing and at worst produces a compile error (if they both have the same type).

I have run into a real-world example of this which produced a compiler error. Arguably it is not best coding practice, however I believe that we could (and should) handle it more gracefully.

I thought of submitting a patch which renames the field assertion to (eg) hasDataField() in the case that it finds a clash. That fixes my immediate problem, however it is imperfect as it introduces other theoretical clash possibilities (eg, if you also had a method called getDataField()). I'm open to other suggestions.

Better handle of assertions inheritance when chaining assertions

For the time being, inheritance is taken into account at generation time as assertions for inherited properties are generated.

if you have a Person with a name and an Employee inheriting from Person with a company property then, the generator will create the following assertions :

  • hasName inPersonAssert`
  • hasName inEmployeeAssert`
  • hasCompany in EmployeeAssert

The idea here would be to generate only hasName in Person and set EmployeeAssert to inherit from PersonAssert.

The advantage would be that any modification in PersonAssert to be reflected to EmployeeAssert (for example if you had a new assertion that was not generated).

We might set a flag to choose between generating assertions for inherited properties or generating an hierarchy of assertions class.

Add hasValue with offset to integer number types

The assertions-generator does not cover the hasValue(x, offset) assert which i would like to have for my current project. I have analyzed the code and it should not be difficult to extend this behavior. Currently a distinction is made:

PRIMITIVE_TYPES = { "int", "long", "short", "byte", "float", "double", "char", BOOLEAN };
REAL_NUMBERS_TYPES = { "float", "double"};

One way could be to introduce a new type which could be look like this:

PRIMITIVE_TYPES = { "int", "long", "short", "byte", "float", "double", "char", BOOLEAN };
PRIMITIVE_NUMBERS_TYPES = { "int", "long", "short", "byte"};
REAL_NUMBERS_TYPES = { "float", "double"};

Every primitive number type will have a hasValue(x) and a hasValue(x, offset). The other code would not be altered.

Another way could be to extend real numbers with hasValue(x)

REAL_NUMBERS_TYPES = { "float", "double","int", "long", "short", "byte"};

That way we would stay closer to the current API of assertj.

What do you think?

Asserts for collections sub types

I'm running the code generator and i'm having this stack:

Full error stack : java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.getParameterizedTypeOf(ClassToClassDescriptionConverter.java:147)
at org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.getTypeDescription(ClassToClassDescriptionConverter.java:120)
at org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.doGetterDescriptionsOf(ClassToClassDescriptionConverter.java:75)
at org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.getterDescriptionsOf(ClassToClassDescriptionConverter.java:62)
at org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.convertToClassDescription(ClassToClassDescriptionConverter.java:51)
at org.assertj.maven.generator.AssertionsGenerator.generateAssertionsFor(AssertionsGenerator.java:103)
at org.assertj.maven.AssertJAssertionsGeneratorMojo.executeWithAssertionGenerator(AssertJAssertionsGeneratorMojo.java:127)
at org.assertj.maven.AssertJAssertionsGeneratorMojo.execute(AssertJAssertionsGeneratorMojo.java:119)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:106)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:317)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:152)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

This happends for a case like this:

public class MyModelClass {
private MyIteratorWrapper iterator;
....
}

public class MyIteratorWrapper implements Iterator {
....
}

public class MyBean {
....
}

In this conditions, i can not autogenerate assertions for MyModelClass

Generator Doesn't Handle Inner Static Classes

We have Avro generated beans that contain a Builder class that look something like this:

public class TestAvroBean extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
  ...
  public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<TestAvroBean>
    implements org.apache.avro.data.RecordBuilder<TestAvroBean> {
    ...

    /** Creates a new Builder */
    private Builder() {
      super(com.simvia.data.model.test.TestAvroBean.SCHEMA$);
    }

 ...
}

Is there a way to prevent the generator from generating Assert classes for inner classes?

Wrong method called for boolean getter

If your actual class has a boolean getter (eg public boolean getFlag()), then the generator tries to generate an assertion for it using the "is" template. This tries to then call the isFlag() method on the actual object, which doesn't exist - so the assertion doesn't compile.

For bean purists it's probably not considered best practice to name your boolean getters as "getFlag()" rather than "isFlag()", but again we should at least be able to handle it gracefully.

Generate assertions with offset for double and float types

I have a class:

public class Hotel {
    public double margin;
}

And generated assertion class

public class HotelAssert extends AbstractAssert<HotelAssert, Hotel> {
    public HotelAssert(Hotel actual) {
        super(actual, HotelAssert.class);
    }

    public HotelAssert hasMargin(double margin) {
        // check that actual Hotel we want to make assertions on is not null.
        isNotNull();

        // overrides the default error message with a more explicit one
        String assertjErrorMessage = "\nExpected margin of:\n  <%s>\nto be:\n  <%s>\nbut was:\n  <%s>";

        // check
        double actualMargin = actual.getMargin();
        if (actualMargin != margin) {
            failWithMessage(assertjErrorMessage, actual, margin, actualMargin);
        }

        // return the current assertion for method chaining
        return this;
    }
}

I want to do something like this:

assertThat(hotel).hasMargin(sample.margin, offset(1.0));

Reference: Assertions class

public static Offset<Double> offset(Double value) {
    return Offset.offset(value);
}

feat(Boolean): Support Boolean Object Type for Boolean assertion generation

Hi,

If I generate the assertion for my following POJO :

public class User {

    private Long id;
    private String login;
    private boolean enabled;

    public User() {
        enabled = true;
    }

    public Long getId() {
        return id;
    }

    public User setId(Long id) {
        this.id = id;
        return this;
    }

    public String getLogin() {
        return login;
    }

    public User setLogin(String login) {
        this.login = login;
        return this;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public User setEnabled(Boolean enabled) {
        this.enabled = enabled;
        return this;
    }
}

all works fine, but if I use the Boolean object type instead of the primitive type boolean, assertions associated to the Boolean field aren't generated.

The file not working :

public class User {

    private Long id;
    private String login;
    private Boolean enabled;

    public User() {
        enabled = true;
    }

    public Long getId() {
        return id;
    }

    public User setId(Long id) {
        this.id = id;
        return this;
    }

    public String getLogin() {
        return login;
    }

    public User setLogin(String login) {
        this.login = login;
        return this;
    }

    public Boolean isEnabled() {
        return enabled;
    }

    public User setEnabled(Boolean enabled) {
        this.enabled = enabled;
        return this;
    }
}

Handle generics of real numbers

The generation of asserts for generics does not handle reals (Double or Float) as expected: Double/Float are processed as Objects, while they should be processed as reals.
Ex:

class Of<T> {
  T value;
}
class OfDouble extends Of<Double> {
}

Actual result:

class OfDoubleAssert extends AbstractAssert<OfDoubleAssert , OfDouble> {
  public OfDoubleAssert hasValue(Comparable avg) {
     ...
  }
}

Expected result:

class OfDoubleAssert extends AbstractAssert<OfDoubleAssert , OfDouble> {
  public OfDoubleAssert hasValue(Comparable avg) {
     ...
  }

  public Double hasValueCloseTo(Double value, Double offset) {
     ...
  }

}

Thanks !

Generated assertions to honour the as() setting

I might be mistaken but it looks to me that the assertions generated by this module don't honour the as() setting. I started trying to do this but wasn't 100% sure of the best way to handle it.

Hamcrest matcher builder

Hi!

I love the DSL to assert an object easily (ie: assertThat(myBean).hasName("foobar").isActivated(); ).
But I also use a lot Mockito which is based on Hamcrest to verify parameters. I would like to reduce the gab between them by having a matcher builder providing the same kind of DSL. Something like:

Matcher<MyBean> matcher = buildMatcher(myBean).hasName("foobar").isActivated();
// I could use it like (mockito):
verify(myMockedBeanDao).save(argThat(matcher));

And why not to have a possibility to use it (or any Hamcrest matcher) like that:

assertThat(myBean).with(matcher);

That's just a thought but it could be a functionality I will use each time I write unit test (almost every day)!

Thanks for considering it
Thomas

Generator error when assertions entry point template class name is changed

If one used the following template :

package ${package};

/**
 * Entry point for assertions of different data types. Each method in this class is a static factory for the
 * type-specific assertion objects.
 */
public class MyAssertions {
${all_assertions_entry_points}
  /**
   * Creates a new <code>{@link Assertions}</code>.
   */
  protected MyAssertions() {
    // empty
  }
}

the generator will still generates a file named Assertions.java instead of MyAssertions.java but the generated content is correct.

Improve error message wording

"\nExpected versionIdPartAsLong of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>";
should be
"\nExpecting versionIdPartAsLong of:\n <%s>\nto be:\n <%s>\nbut was:\n <%s>";

String comparison issue

Following code will be always pass

String expected = "CHANGE PHONE NUMBER667676767";
softly.assertThat(changePhoneNumberPage.getPageHeader().getText().equals(expected)).isTrue();

where
changePhoneNumberPage.getPageHeader().getText()="CHANGE PHONE NUMBER"

Predicate assertions are badly generated if boolean property contains is

 public PropertyDomainEventAssert<S, T> isDisabled() {
    // check that actual PropertyDomainEvent we want to make assertions on is not null.
    isNotNull();

    // check
    if (!actual.isDisabled()) {
      failWithMessage("\nExpecting that actual PropertyDomainEvent is dabled but is not.");
    }

    // return the current assertion for method chaining
    return this;
  }

Generate soft assertions

assertj-core has soft assertions allowing to gather error messages.
we can generate a SoftAssertions similar to Assertions allowing such a feature.

Bad generated code in contains assertion for iterable property with ? extends wildcard

Generated assertions corresponding to :

Collection<? extends Attribute> getAttributes();

is (shorten for brevety sake):

public S hasAttributes(Attribute... attributes) {
  Assertions.assertThat(actual.getAttributes()).contains(attributes);
  return myself;
}

It causes a compile error:

The method contains(capture#1-of ? extends Attribute...) in the type AbstractIterableAssert<IterableAssert<capture#1-of ? extends Attribute>,Iterable<capture#1-of ? extends Attribute>,capture#1-of ? extends Attribute> is not applicable for the arguments (Attribute[])

Generator does not handle correctly several inner classes with the same name

I'm using the maven generator, configured to generate assertions for classes in com.foo.package.

com.foo.package has 2 classes : Bean1 and Bean2. Each one of them has a public static inner class called Block. So we have Bean1.Block and Bean2.Block.

The generator generates a BlockAssert with this header :
public class BlockAssert extends AbstractAssert<BlockAssert, Bean1.Block>

but generates ย :

   * Creates a new instance of <code>{@link BlockAssert}</code>.
   *
   * @param actual the actual value.
   * @return the created assertion object.
   */
  public static BlockAssert assertThat(Bean2.Block actual) {
    return new BlockAssert(actual);
  }

Thus Assertions.java cannot compile.

The generator should create different Assert classes for each Block.

Assertation generation throws when generating assertions for scala case class

First: thanks for your great assertion generator!

I was trying to use the maven plugin to generate assertions for a mixed java/scala project. I reported it here, because I think it is related to generation instead of the maven plugin. It turns out the generator throws the following exception when a assertion classes are generated for a case class or object.

[INFO] --- assertj-assertions-generator-maven-plugin:1.2.0:generate-assertions (default) @ AssertJAssertionsGenerationsBugWithScala ---
[INFO] 

====================================
AssertJ assertions generation report
====================================

--- Generator input parameters ---


--- Generator results ---

Assertions failed with error : Illegal group referenceFull error stack : java.lang.IllegalArgumentException: Illegal group reference
    at java.util.regex.Matcher.appendReplacement(Matcher.java:808)
    at java.util.regex.Matcher.replaceAll(Matcher.java:906)
    at java.lang.String.replaceAll(String.java:2162)
    at org.assertj.assertions.generator.BaseAssertionGenerator.generateCustomAssertionContentFor(BaseAssertionGenerator.java:224)
    at org.assertj.assertions.generator.BaseAssertionGenerator.generateCustomAssertionFor(BaseAssertionGenerator.java:198)
    at org.assertj.maven.generator.AssertionsGenerator.generateAssertionsFor(AssertionsGenerator.java:49)
    at org.assertj.maven.AssertJAssertionsGeneratorMojo.executeWithAssertionGenerator(AssertJAssertionsGeneratorMojo.java:83)
    at org.assertj.maven.AssertJAssertionsGeneratorMojo.execute(AssertJAssertionsGeneratorMojo.java:75)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

I made a small project to show the bug at https://github.com/TimSoethout/AssertJAssertionsGenerationsBugWithScala

In the file src/main/scala/pack/Scala.scala I created a case class. This will trigger above message on a build (mvn clean package).
It also fails when the case class is replaced with an object; this can be found on branch object.

Use fully qualified class names instead of generating imports

I will have a lot of benefits:

  • avoid errors when two classes with the same name (but different package) are used
  • simplify code
  • avoid unused imports

Unused imports happened when generating assertions for a Collection property or Map.

Ex :

public interface AttributeValuesGetter {
    public java.util.Map<test.AttributeSchema, java.util.Collection<test.AttributeValue>> getAttributeValuesMap();
}

We should probably try to detect any unused import at the latest step of assertion class generation.

switch the property/field templates over to use the 'navigation' approach by default?

Once this PR is merged and issue fixed #67 along with the NavigationListAssert class in assertj-core: assertj/assertj#641 it would be easy to switch the OOTB templates in the generator to use the 'navigation' model approach.

So that for every property of an object we generate exactly one navigation method that lets users chain assertions together; reusing all the methods from ListAssert and NavigationListAssert for iterable properties or the custom typed assertions for other properties.

This would result in much smaller code generated for the assertion classes and much more power. The only downside is some of the current methods would be a tad more verbose.

e.g. for a generated assertion class with a name property the current generated code would be:

// current generated code
assertThat(person).hasName("James");

// new minimal code
assertThat(person).name().isEqualTo("James");
assertThat(person).name().contains("m");
...

Ditto for iterable properties right now we generate a few methods which are mostly already included in ListAssert. e.g. all these assertion methods are available on any generated iterable property method:
https://github.com/jstrachan/assertj-core/blob/7b1d079edeb5ac984cebbed77a65025718ee7673/src/test/java/org/assertj/core/navigation/ListNavigation_Test.java#L56-L62

Removing the old generated methods would break folks code I guess; so maybe we should add a flag to switch to the new more concise model?

If you are interested; here are the 2 new templates (which need minor tweaks to reuse the assertj/assertj#641 code):

add properties ${propertySimpleType} and ${propertyAssertType} so we can generate nicer navigation assertion methods

there's a back ground issue from our project here:
fabric8io/fabric8#5925

the general idea is we want to generate helper methods in the generated Assert classes to aid navigation through deeply nested models. The background is the Kubernetes model is very deeply nested.

For a complex model where you want to write assertions like:

assertThat(foo.getBar().getThing()).isNotNull()

the problem is the getBar() could return null as could the getThing().

So we wanna do this instead...

assertThat(foo).bar().thing().isNotNull();

where each property method bar() and thing() are kinda like the hasBar() function thats generated OOTB, only it returns the assertThat() of the value. So the last assertion - .isNotNull() could be anything really; isEqualTo() or whatever.

e.g. we generate functions like this:

class FooAssert ... {

   public BarAssert bar() {
      isNotNull();

      return (BarAssert) assertThat(actual.getBar()).describedAs(toString() + ".bar");
  }
}

I've managed to implement the above in our project using the extensible templates (thanks for that!) - but to do so I needed to add the above 2 properties to the templates. Actually as of writing only the 2nd one is required but figured I may as well submit a PR for both ;)

Create assertions for private fields

It would be nice if you could generate assertion classes which include assertion methods for private fields.

The assertion could make use of the FieldSupport introduced here: assertj/assertj#144

Maybe some option should be provided to disable this feature because i could imagine that not everyone would be interested in seeing those kind of assertion methods

Unable to generate assertions for classes with same name but different package

I duplicate this issue : assertj/assertj-assertions-generator-maven-plugin#19 because the issue is on this project and not in the maven-plugin.

The problem is when you have some classes with same name but a differents references (packages), *Assertions.java didn't compile (due to some collisions)

Moreover, there is only one assertThat method created.

Maybe one fix could be to remove imports and always use the fully qualifier name, but it's a huge change for this project.

To reproduce this issue, you can copy a class into another package and try to generate assertions for both, *Assertions.java files will not compile.

Generate an entry point for generated Assert classes (like Assertions)

There is an example of such class in assertj-examples:

 // extending make all standard AssertJ assertions available.
public class MyProjectAssertions extends Assertions {

  // add the custom assertions related to MyProject

  public static TolkienCharacterAssert assertThat(TolkienCharacter actual) {
    return new TolkienCharacterAssert(actual);
  }

  public static HumanAssert assertThat(Human actual) {
    return new HumanAssert(actual);
  }

  public static EmployeeAssert assertThat(Employee actual) {
    return new EmployeeAssert(actual);
  }

  public static EmployeeOfTheMonthAssert assertThat(EmployeeOfTheMonth actual) {
    return new EmployeeOfTheMonthAssert(actual);
  }

}

Generated Assertions entry point should (could?) extend default Assertions entry point

Right now, a static import of my.pakkage.Assertions.assertThat means I can't do assertThat("a string").isNotEmpty(), for example. If my.pakkage.Assertions extended org.assertj.core.api.Assertions, I could do that.

Maybe add a configuration property to have generated entry points optionally extend the default one?

I do know I can achieve this with a custom template, but it feel too cumbersome for that.

Allow user to register templates for any type.

For example, a user wants to generate more assertions for String properties.
If String property is name, we only generate hasName, if we are able to register a template for String, users may tweak which assertions are generated for String and add hasNameStartingWith (for example).

Property style abstract class methods ignored when generating assertions

The root of my problem comes from trying to use AutoValue with AssertJ generated assert classes. AutoValue supports property style method calls - x() - as well as standard getter methods - getX(). I prefer property style since the AutoValue classes are designed to be immutable and this makes things more concise. Here is an example class.

@AutoValue
public abstract class Sample {

    public static Sample create(String title) { return new AutoValue_Sample(-1, title); }

    public abstract long id();
    public abstract String title();
}

Would it be possible to support this use case?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.