创建一个类MyFavor用于描述你个人喜好的一类东西,必须包含至少三个属性用于描述清楚该爱好,至少两个方法和至少两个构造器,同时写测试类,测试该类中的所有构造器、方法和属性。用java实现
时间: 2024-10-13 21:14:09 浏览: 19
首先,我们创建一个名为`MyFavor`的类,用于描述个人喜好:
```java
public class MyFavor {
private String name; // 爱好名称
private int frequency; // 活动频率,单位:次/月
private List<String> details; // 具体活动细节
// 使用默认构造器
public MyFavor() {
this.name = "";
this.frequency = 0;
this.details = new ArrayList<>();
}
// 参数化构造器
public MyFavor(String name, int frequency, String... details) {
this.name = name;
this.frequency = frequency;
this.details.addAll(Arrays.asList(details));
}
// 方法:获取爱好名称
public String getName() {
return name;
}
// 方法:设置爱好名称
public void setName(String name) {
this.name = name;
}
// 方法:获取活动频率
public int getFrequency() {
return frequency;
}
// 方法:设置活动频率
public void setFrequency(int frequency) {
this.frequency = frequency;
}
// 方法:获取活动详情列表
public List<String> getDetails() {
return details;
}
// 方法:添加活动详情
public void addDetail(String detail) {
this.details.add(detail);
}
}
```
接下来,我们创建一个测试类`MyFavorTest`来测试这个类:
```java
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MyFavorTest {
@Test
void testDefaultConstructor() {
MyFavor myFavor = new MyFavor();
assertEquals("", myFavor.getName());
assertEquals(0, myFavor.getFrequency());
assertTrue(myFavor.getDetails().isEmpty());
}
@Test
void testParameterizedConstructor() {
MyFavor myFavor = new MyFavor("Reading", 4, "Novels", "Magazines");
assertEquals("Reading", myFavor.getName());
assertEquals(4, myFavor.getFrequency());
assertEquals(Arrays.asList("Novels", "Magazines"), myFavor.getDetails());
}
@Test
void testSetNameAndAddDetail() {
MyFavor myFavor = new MyFavor();
myFavor.setName("Cooking");
myFavor.addDetail("Baking");
assertEquals("Cooking", myFavor.getName());
assertEquals(0, myFavor.getFrequency()); // 初始化频率为0
assertEquals(List.of("Baking"), myFavor.getDetails());
}
@Test
void testInvalidFrequency() {
assertThrows(IllegalArgumentException.class, () -> new MyFavor("Gaming", -1, "PC Games"));
}
}
```
在这个测试类中,我们分别检查了默认构造器、参数化构造器以及`setName()`和`addDetail()`方法的正确工作情况,并验证了异常处理机制是否正常运行。
阅读全文