baeldung-articles : BAEL-6752 (#16195)
* baeldung-articles : BAEL-6752 When to Use Setter Methods or Constructors for Setting a Variable's Value in Java. * baeldung-articles : BAEL-6752 When to Use Setter Methods or Constructors for Setting a Variable's Value in Java. * Updating ConstructorsVersusSetterMethodsUnitTest.java Rename functions
This commit is contained in:
parent
74cd524de2
commit
9cc307e108
@ -0,0 +1,26 @@
|
||||
package com.baeldung.constructorversussettermethod;
|
||||
|
||||
public class Product {
|
||||
private String name;
|
||||
private double price;
|
||||
private String category;
|
||||
|
||||
public Product(String name, double price, String category) {
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.constructorversussettermethod;
|
||||
|
||||
public class User {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
if (username.matches("[a-zA-Z0-9_]+")) {
|
||||
this.username = username;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid username format");
|
||||
}
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
if (password.length() >= 8) {
|
||||
this.password = password;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Password must be at least 8 characters long");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.constructorversussettermethod;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ConstructorsVersusSetterMethodsUnitTest {
|
||||
@Test
|
||||
public void givenNewUser_whenSettingUsername_thenUsernameIsSet() {
|
||||
User user = new User();
|
||||
user.setUsername("john_doe");
|
||||
assertEquals("john_doe", user.getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewUser_whenSettingPassword_thenPasswordIsSet() {
|
||||
User user = new User();
|
||||
user.setPassword("strongPassword123");
|
||||
assertEquals("strongPassword123", user.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProductDetails_whenCreatingProductWithConstructor_thenProductHasCorrectAttributes() {
|
||||
Product product = new Product("Smartphone", 599.99, "Electronics");
|
||||
assertEquals("Smartphone", product.getName());
|
||||
assertEquals(599.99, product.getPrice(), 0.001);
|
||||
assertEquals("Electronics", product.getCategory());
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user