I have the following example situation:
public void shouldReturnStringForEnum() {
MessageType myType = getType();
System.out.println(getMessageForType(myType));
}
String getMessageForType(MessageType myType) {
switch(myType) {
case error:
return "Error type";
case warning:
return "Warning type";
case info:
return "Info type";
}
} // <= error: missing return statement
MessageType getType() {
Random random = new Random();
return MessageType.values()[random.nextInt(3)];
}
enum MessageType {error, warning, info }
我无法确定除了switch
语句体之外的方法getMessageForType
返回的可能性。
我正在考虑:
- 从I/O数据进行反序列化 - 但是在调用
getMessageForType
之前很久就会发生java.lang.IllegalArgumentException: No enum constant
- 可能为空的方法参数 - 但是它将在评估
switch(myType)
时失败,出现java.lang.NullPointerException
在这种情况下强制使用默认返回语句是不舒服的,因为我不知道在这里返回什么。在这种情况下抛出异常也没有意义。这种行为背后的设计决策是什么?
请帮忙看看,我错过了什么?
myType.getWhateverText()
!B)用@Test注释的测试如果没有进行assert或其他类型的真实验证...而只是print...那就不是一个测试;-) - GhostCat