BAEL-6491 - Why is Field Injection not Recommended? (#14146)

This commit is contained in:
Ana Peterlić 2023-06-06 15:17:16 +02:00 committed by GitHub
parent a66251654d
commit 0d8db7af6a
3 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.fieldinjection;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
public static final String INVALID_EMAIL = "Invalid email";
private final EmailValidator emailValidator;
public EmailService(final EmailValidator emailValidator) {
this.emailValidator = emailValidator;
}
public void process(String email) {
if (!emailValidator.isValid(email)) {
throw new IllegalArgumentException(INVALID_EMAIL);
}
// ...
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.fieldinjection;
import org.springframework.stereotype.Component;
import java.util.regex.Pattern;
@Component
public class EmailValidator {
private static final String REGEX_PATTERN = "^(.+)@(\\S+)$";
public boolean isValid(final String email) {
return Pattern.compile(REGEX_PATTERN)
.matcher(email)
.matches();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.fieldinjection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class EmailServiceUnitTest {
private EmailValidator emailValidator;
private EmailService emailService;
@BeforeEach
public void setup() {
this.emailValidator = Mockito.mock(EmailValidator.class);
this.emailService = new EmailService(emailValidator);
}
@Test
void givenInvalidEmail_whenProcess_thenThrowException() {
String email = "testbaeldung.com";
when(emailValidator.isValid(email)).thenReturn(false);
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> emailService.process(email));
assertNotNull(exception);
assertEquals(EmailService.INVALID_EMAIL, exception.getMessage());
}
}