【问题标题】:How to test if a variable exists using JUnit 5?如何使用 JUnit 5 测试变量是否存在?
【发布时间】:2020-12-02 14:02:54
【问题描述】:

我想测试一下JUnit测试中是否存在变量。

我有一个名为 animal 的类,它是一个抽象类。


public abstract class Animal {
    private final int age;
    private final int speed;
    
    public Animal (int age,int speed) {
        this.age = age;
        this.speed = speed;
    }
    public static void main(String[] args) {
    }
    @Override 
    public boolean equals(Object anotherObject) {
           if (this == anotherObject) {  
                  return true;  
              }else {
                  return false;
              }
    }
    public abstract Animal[] multiply(int n);
    
    private boolean isFaster(Animal a) {
        if(this.getSpeed() >a.getSpeed()) {
            return true;
        }else {
        return false;
        }
    }
    
    private boolean isOlder(Animal a) {
        if(this.getAge() >a.getAge()) {
            return true;
        }
        return false;
    }
    @Override
    public String toString() {
        return this.getClass()+ "is " + this.getAge() + " years old, is " +this.getSpeed() +" units fast.";
        
    }
    public final int getAge() {
        return age;
    }

    public final int getSpeed() {
        return speed;
    }



}

我想测试一下变量 age 是否存在,以及它是否是私有的和最终的。我如何在 Junit 测试中做到这一点?

【问题讨论】:

  • exists 是什么意思?你的意思是它有没有价值?
  • 我的意思是它更像是检查类 Animal 有一个名为 age 的变量,而不一定是赋值。
  • 既然age是在类中声明的,它怎么可能“不存在”?
  • @ArvindKumarAvinash 怎么样?您不能从类中删除属性,因此如果抽象基类具有属性,则无论您是否愿意,它们都存在于所有实现类中。
  • @Gimby - 你是对的,但 OP 的问题只是检查一个成员是否存在于一个类中。

标签: java unit-testing testing junit junit5


【解决方案1】:

你可以这样做:

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.lang.reflect.Field;
import java.util.Arrays;

import org.junit.jupiter.api.Test;

class TestAnimal {
    @Test
    void testAge() {
        Field[] fields = Animal.class.getDeclaredFields();
        assertEquals(true, Arrays.stream(fields).anyMatch(f -> f.getName().equals("age")));
        for (Field f : fields) {
            if (f.getName().equals("age")) {
                assertEquals(0, f.toGenericString().indexOf("private"));
                assertEquals(true, f.toGenericString().contains("final"));
                break;
            }
        }

    }
}

查看Field 的文档页面以了解有关Field#getNameField#toGenericString 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2018-06-16
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多