Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object generation does not fail when setter invocation fails #400

Closed
fmbenhassine opened this issue Mar 24, 2020 · 0 comments
Closed

Object generation does not fail when setter invocation fails #400

fmbenhassine opened this issue Mar 24, 2020 · 0 comments
Labels
Milestone

Comments

@fmbenhassine
Copy link
Member

fmbenhassine commented Mar 24, 2020

As of v4.2, Easy Random does not fail when a setter invocation fails. Here is a quick example with a failing test:

public class Person {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age must be positive");
        }
        this.age = age;
    }
}

@Test
void shouldFailIfSetterInvocationFails() {
    EasyRandom easyRandom = new EasyRandom();
    Assertions.assertThrows(ObjectCreationException.class, 
                            () -> easyRandom.nextObject(Person.class));
}

This test fails and the person instance is generated with a negative age, which is not intended by the class designer.

As a class designer, if I want to enforce some rules while setting fields to make sure my object's internal state is valid, I do not want Easy Random or any other library to bypass my setter and create invalid instances of my class, unless I explicitly tell the library to do so (with an option like bypassSetters, see #398 ).

If one wants the library to generate valid values without bypassing setters, one can register a custom randomizer for the target field. For the previous example, it could be:

EasyRandomParameters parameters = new EasyRandomParameters()
            .randomize(FieldPredicates.named("age").and(inClass(Person.class)), new IntegerRangeRandomizer(1, 150));
EasyRandom easyRandom = new EasyRandom(parameters);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant