Java:实现Dog类年龄递增逻辑并通过单元测试(已解决)
已解决:狗年龄递增功能实现问题
需求说明
仅允许将狗的年龄递增,不可减少。在小型狗登记程序中,选择“增加狗年龄”选项时,无需用户输入,直接将当前年龄加1即可。
问题背景
最初实现的setAge方法无法通过单元测试,报错年龄未递增,改用increaseAgeByOne方法后解决了测试问题。
原setAge方法代码
public void setAge(int newAge) { if (newAge > this.age) { this.age = newAge; } else { System.out.println("Age cannot decrease. Keeping the current age."); } }
解决测试问题的increaseAgeByOne方法代码
public void increaseAgeByOne() { if (age < Integer.MAX_VALUE) { age++; } else { System.out.println("Age cannot be increased further due to overflow."); } }
Dog类核心代码
public class Dog { private String name; private String breed; private int age; private int weight; private double tailLength; private static final double TAIL_LENGTH_FOR_DACHSHUND = 3.7; public Dog(String name, String breed, int age, int weight) { this.name = name; this.breed = breed; this.age = age; this.weight = weight; this.tailLength = tailLength; normalLetters(); } public String getName() { return name; } public String getBreed() { return breed; } public int getAge() { return age; } public void setAge(int newAge) { if (newAge > this.age) { this.age = newAge; } else { System.out.println("Age cannot decrease. Keeping the current age."); } } ... }
对应的单元测试用例
@Test @Order(130) @DisplayName("Age can be updated") public void ableToIncreaseAge() { Dog dog; dog = new Dog(DEFAULT_NAME, DEFAULT_BREED, DEFAULT_AGE, DEFAULT_WEIGHT); callAssumedMethodForIncreasingAgeOfDog(dog, 1); assertEquals(DEFAULT_AGE + 1, dog.getAge()); dog = new Dog(DEFAULT_NAME, DEFAULT_BREED, DEFAULT_AGE, DEFAULT_WEIGHT); callAssumedMethodForIncreasingAgeOfDog(dog, 3); assertEquals(DEFAULT_AGE + 3, dog.getAge()); } @Test @Order(140) @DisplayName("Age cannot decrease") public void unableToDecreaseAge() { Dog dog; dog = new Dog(DEFAULT_NAME, DEFAULT_BREED, DEFAULT_AGE, DEFAULT_WEIGHT); callAssumedMethodForIncreasingAgeOfDog(dog, -1); assertEquals(DEFAULT_AGE, dog.getAge()); } @Test @Order(150) @DisplayName("Age cannot decrease through overflow") public void unableToDecreaseAgeThroughOverflow() { Dog dog; dog = new Dog(DEFAULT_NAME, DEFAULT_BREED, Integer.MAX_VALUE, DEFAULT_WEIGHT); callAssumedMethodForIncreasingAgeOfDog(dog, 1); assertEquals(Integer.MAX_VALUE, dog.getAge()); }
内容的提问来源于stack exchange,提问作者Teodora Kovacevic
相关产品推荐
相关产品推荐

