如何测试枚举类型? [英] How to test enum types?

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

问题描述

我正在尝试为一个小型图书馆构建一套或多或少的完整单元测试。由于我们希望允许不同的实现存在,我们希望这套测试是(a)通用的,所以我们可以重新使用它来测试不同的实现和(b)尽可能的完整。对于(b)部分,我想知道是否有最佳实践来测试枚举类型。所以例如我有一个枚举如下:

I'm currently trying to build a more or less complete set of unit tests for a small library. Since we want to allow different implementations to exist we want this set of tests to be (a) generic, so that we can re-use it to test the different implementations and (b) as complete as possible. For the (b) part I'd like to know if there is any best-practice out there for testing enum types. So for example I have an enum as follows:

public enum Month {
    January,
    February,
    ...
    December;
}

这里我想确保所有的枚举类型真的存在。这甚至是必要的吗?目前我正在使用Hamcrests assertThat ,如下例所示:

Here I want to ensure that all enum types really exist. Is that even necessary? Currently I'm using Hamcrests assertThat like in the following example:

assertThat(Month.January, is(notNullValue()));

缺少1月枚举将导致编译时错误,可以通过创建缺少的枚举类型。

A missing "January" enum would result in a compile time error which one can fix by creation the missing enum type.

我在这里使用Java,但我不介意,如果你的答案是不同的语言..

I'm using Java here but I don't mind if your answer is for a different language..

编辑:

由于mkato和Mark Heath都指出测试枚举可能不是必需的,因为编译器不会当您使用不在那里的枚举类型时进行编译。但是我仍然想测试这些枚举,因为我们想要构建一个独立的TCK类的test.jar,它将对不同的实现运行相同的测试。所以我的问题更像是:测试枚举类型的最好方法是什么?

As mkato and Mark Heath have both pointed out testing enums may not be necessary since the compiler won't compile when you are using an enum type which isn't there. But I still want to test those enums since we want to build a seperate TCK-like test.jar which will run the same test on different implementations. So my question was more meant to be like: What is the best way to test enum types?

在考虑一下之后,我将Hamcrest语句更改为:

After thinking about it a bit more I changed the Hamcrest statement above to:

assertThat(Month.valueOf("January"), is(notNullValue()));

当一月不存在时,此语句现在会抛出NPE(尚未)。这种方法有什么问题吗?

This statement now throws a NPE when January is not there (yet). Is there anything wrong with this approach?

推荐答案

对于枚举,我只测试他们,只有当他们实际上有方法。如果这是一个纯粹的只有价值的枚举,就像你的例子,我会说不要打扰。

For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

但是,由于你热衷于测试它,你的第二个选项比第一个好多了。第一个问题是,如果您使用IDE,枚举上的任何重命名也将重命名测试类中的那些。

But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

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

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