FlexTradeUKLtd / jfixture

JFixture is an open source library based on the popular .NET library, AutoFixture
MIT License
105 stars 22 forks source link

NPE when creating generic type #29

Closed pwfcurry closed 8 years ago

pwfcurry commented 8 years ago
public class TestClass {

  private final TestContainer<String> container;

  public TestClass(TestContainer<String> container) {
    this.container = container;
  }

  public class TestContainer<T> {

    private final T value;

    public TestContainer(T value) {
      this.value = value;
    }
  }

  public static void main(String[] args) {
    new JFixture().create(TestClass.class);
  }

}

Running the above code causes JFixture v2.5.1 to throw a NPE:

Exception in thread "main" java.lang.NullPointerException
    at com.flextrade.jfixture.utility.SpecimenType.<init>(SpecimenType.java:37)
    at com.flextrade.jfixture.utility.SpecimenType$3.<init>(SpecimenType.java:55)
    at com.flextrade.jfixture.utility.SpecimenType.withGenericContext(SpecimenType.java:55)
    at com.flextrade.jfixture.utility.ParameterUtils.convertPossibleGenericTypeToSpecimenType(ParameterUtils.java:50)
richkeenan commented 8 years ago

Java and generics. The bane of my life. Thanks @pwfcurry I'll take a look

richkeenan commented 8 years ago

Interestingly this works fine if TestContainer isn't an inner class

richkeenan commented 8 years ago

As suspected, this isn't an issue with Generics, it's an issue with the inner type. Your definition would cause a circular reference as TestClass requires TestContainer in the constructor but TestContainer implicitly takes an instance of TestClass because it's an inner class not marked as static.

You can't create an instance of TestClass whether you're using JFixture or not (unless you pass a null TestContainer in). If you modify TestContainer to be static JFixture will handle this correctly.

Maybe your simplified example is missing something else that your actual code has? I'm closing this issue but if you can reproduce it (and be able to create the class in 'regular' Java) please raise a new issue and I'll love to look into it.

pwfcurry commented 8 years ago

Oops, bad example. I still see the same problem when TestContainer is static, also when it's not an inner class.