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

查看:1297
本文介绍了如何使用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()函数。

此问题的类似问题是< a href =https://stackoverflow.com/questions/3604721/how-to-test-a-method-in-an-abstract-class-with-abstract-methods>这里,但它是不使用JUnit。

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

在JUnit FAQ部分,我发现这个链接,但我不明白作者想用这个例子说什么。这行代码是什么意思?

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.

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

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天全站免登陆