An attempt to reimplement core features of a popular .NET anonymous value generator - AutoFixture - in Java
Maven xml pom can be obtained at: http://mvnrepository.com/artifact/com.github.autofixture/autofixturegenerator
New fixture object:
Fixture fixture = new Fixture();
A value of non-generic class:
int number = fixture.create(int.class);
String text = fixture.create(String.class);
A value of generic class (including collections):
ArrayList<Integer> list = fixture.create(new InstanceOf<ArrayList<Integer>>() {});
Customizations always take precedence over built-in generators.
Example of new integer generation customization that always returns 12:
f.register(new InstanceGenerator() {
@Override
public <T> boolean appliesTo(InstanceType<T> arg0) {
return arg0.getRawType() == int.class;
}
@SuppressWarnings("unchecked")
@Override
public <T> T next(InstanceType<T> arg0, FixtureContract arg1) {
return (T) Integer.valueOf(12);
}
@Override
void setOmittingAutoProperties(boolean isOn) {}
});
Clearing all customizations:
fixture.clearCustomizations();
Starting with version 0.3.0, new "any" method helpers are available.
import static autofixture.publicinterface.*;
public class AnyGenerationMethodsSpecification {
@Test
public void shouldGenerateEachTimeDifferentString() {
String str1 = Any.string();
String str2 = Any.string();
assertThat(str1, is(not(str2)));
}
@Test
public void shouldGenerateEachTimeDifferentInstance() {
GenericObject<Integer> o1 = Any.anonymous(new InstanceOf<GenericObject<Integer>>() {});
GenericObject<Integer> o2 = Any.anonumous(new InstanceOf<GenericObject<Integer>>() {});
assertThat(o1, is(not(o2)));
}
}
For more examples of this feature and syntax variants, see acceptance tests