Merge pull request #5577 from pvangool/BAEL-2074

BAEL-2074: Lombok builder with custom setter
This commit is contained in:
Loredana Crusoveanu 2018-10-31 20:24:19 +02:00 committed by GitHub
commit 2c0113d073
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 77 additions and 0 deletions

View File

@ -4,3 +4,4 @@
- [Using Lomboks @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean)
- [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance)
- [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value)
- [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-with-custom-setter)

View File

@ -0,0 +1,39 @@
package com.baeldung.lombok.builder.customsetter;
import java.io.File;
import java.util.List;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class Message {
private String sender;
private String recipient;
private String text;
private File file;
public static class MessageBuilder {
private String text;
private File file;
public MessageBuilder text(String text) {
this.text = text;
verifyTextOrFile();
return this;
}
public MessageBuilder file(File file) {
this.file = file;
verifyTextOrFile();
return this;
}
private void verifyTextOrFile() {
if (text != null && file != null) {
throw new IllegalStateException("Cannot send 'text' and 'file'.");
}
}
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.lombok.builder.customsetter;
import java.io.File;
import org.junit.Test;
public class BuilderWithCustomSetterUnitTest {
@Test
public void givenBuilderWithCustomSetter_TestTextOnly() {
Message message = Message.builder()
.sender("user@somedomain.com")
.recipient("someuser@otherdomain.com")
.text("How are you today?")
.build();
}
@Test
public void givenBuilderWithCustomSetter_TestFileOnly() {
Message message = Message.builder()
.sender("user@somedomain.com")
.recipient("someuser@otherdomain.com")
.file(new File("/path/to/file"))
.build();
}
@Test(expected = IllegalStateException.class)
public void givenBuilderWithCustomSetter_TestTextAndFile() {
Message message = Message.builder()
.sender("user@somedomain.com")
.recipient("someuser@otherdomain.com")
.text("How are you today?")
.file(new File("/path/to/file"))
.build();
}
}