简体   繁体   中英

How to test when bean is using a custom Lombok Builder

The following code works where my bean is using Lombok Builder annotations with a custom builder.

I am having issues with testing when I want to create this bean with values. I can no longer use Setters (intentional) and can't just use.builder() due to the custom builder.

My question is, how do I create this bean in my tests? Note that I do want to use a builder and not looking to use Lombok's @Value annotation. The custom builder is necessary to work with Jackson.

One possibility I can think of is to add a constructor inside the custom builder which I hopefully don't need to do just for the sake of testing.

Please advice. Thanks.

Working Bean setup.

@Getter
@JsonDeserialize(builder = MyData.MyDataBuilder.class)
@Builder(builderClassName = "MyDataBuilder", toBuilder = true)
public class MyData {
    @JsonProperty("some_key")
    private String skey;
    @JsonProperty("name")
    private String name;

    // needed to work with Jackson
    @JsonPOJOBuilder(withPrefix = "")
    static class MyDataBuilder {}
}

Test trying to create the Object. Following won't work as mentioned above.

MyData.builder()
    .skey("12345")
    .name("some_name")
    .build();

or

MyData myData = new MyData();
myData.skey("12345");
myData.name("some_name");

You can customize the builder class to have any access level you want. Lombok makes it public by default if you don't customize it.

If the class itself and at least one constructor are public , it is possible to create instances from everywhere (not just the same package). But then there is no reason in most cases why the builder class should not be public , too: If the builder pattern is beneficial in its package, it will probably also be beneficial everywhere else.

If you don't want your class to be instantiated in other packages, then the builder should not be public (and also no constructor). However, then your test is also somehow flawed or in the wrong package.

So either make the custom builder class public , or change your test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM