如何使用 JUnit 测试 Java 中的抽象类? [英] How to test abstract class in Java with JUnit?

查看:24
本文介绍了如何使用 JUnit 测试 Java 中的抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 JUnit 进行 Java 测试的新手.我必须使用 Java,我想使用单元测试.

I am new to Java testing with JUnit. I have to work with Java and I would like to use unit tests.

我的问题是:我有一个带有一些抽象方法的抽象类.但是有一些方法不是抽象的.如何使用 JUnit 测试此类?示例代码(很简单):

My problem is: I have an abstract class with some abstract methods. But there are some methods which are not abstract. How can I test this class with JUnit? Example code (very simple):

abstract class Car {

    public Car(int speed, int fuel) {
        this.speed = speed;
        this.fuel = fuel;
    }

    private int speed;
    private int fuel;

    abstract void drive();

    public int getSpeed() {
        return this.speed;
    }

    public int getFuel() {
        return this.fuel;
    }
}

我想测试 getSpeed()getFuel() 函数.

I want to test getSpeed() and getFuel() functions.

与此问题类似的问题是 here,但它没有使用 JUnit.

Similar question to this problem is here, but it is not using JUnit.

在 JUnit 常见问题部分,我找到了 这个链接,但我不明白是什么作者想用这个例子来说明.这行代码是什么意思?

In JUnit FAQ section, I found this link, but I don't understand what the author want to say with this example. What does this line of code mean?

public abstract Source getSource() ;

推荐答案

如果您没有类的具体实现并且方法不是 static 测试它们的意义何在?如果您有一个具体类,那么您将测试这些方法作为具体类公共 API 的一部分.

If you have no concrete implementations of the class and the methods aren't static whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.

我知道你在想什么我不想一遍又一遍地测试这些方法,这就是我创建抽象类的原因",但我的反驳论点是单元测试的重点是允许开发人员进行更改、运行测试并分析结果.这些更改的一部分可能包括覆盖抽象类的方法,包括 protectedpublic,这可能会导致基本的行为变化.根据这些更改的性质,它可能会影响您的应用程序以意外的、可能是负面的方式运行.如果你有一个好的单元测试套件,这些类型的变化引起的问题在开发时应该很明显.

I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected and public, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.

这篇关于如何使用 JUnit 测试 Java 中的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆