在 Java 等强类型语言中,无需显式检查返回对象的类型,因为如果返回类型与方法签名不匹配,代码将无法编译。前任。当需要整数时,您不能返回 bool 值。
在 Ruby、JavaScript、Python 等松散类型语言中,可以返回任何内容。编写检查从方法返回的对象类型的单元测试是否有意义?在我看来,这将确保在需要 bool 值的地方返回 bool 值。
有必要在下面进行单元测试吗?
=============================
Ruby 示例的尝试:
first_module.rb:
module FirstModule
TypeA = Struct.new(
:prop1,
:prop2)
self.create_type_a
TypeA.new(
'prop1Val',
'prop2Val')
end
end
type_a_repository.rb:
module TypeARepository
def self.function_to_test
FirstModule.create_type_a # This will return TypeA object
end
end
type_a_repository_spec.rb:
RSpec.describe '' do
describe '' do
before do
allow(FirstModule).to receive(:create_type_a)
.and_return(FirstModule.create_type_a)
end
it '' do
result = TypeARepository.function_to_test
expect(result).to be_a(FirstModule::TypeA) # is this necessary?
end
end
end
最佳答案
如果您雇用 programming by contract那么答案通常是“否”,因为只要返回值符合预期标准(通常非常宽松),那么您就不能提示。
例如:
# Adds together zero or more integer values and returns the sum
def sum(*numbers)
numbers.inject(0,:+)
end
测试时你会做这样的事情:
assert_equal 0, sum
assert_equal 1, sum(1)
assert_equal 0, sum(1, -1)
现在当您提供非整数值时会发生什么?
sum('1')
# => Exception: String can't be coerced into Integer
原始契约(Contract)并未将其指定为有效用例,因此有理由异常(exception)。如果要扩大范围:
# Adds together zero or more numerical values and returns the sum
def sum(*numbers)
numbers.map(&:to_i).inject(0,:+)
end
现在您可以将非整数值相加:
assert_equal 6, sum(1, 2.0, '3')
请注意,只要结果通过断言测试,您就一直满意。在 Ruby 6.0
中,6
和 "6"
都是不同的,不等价的,所以不用担心得到错误的类型。
这在其他语言中可能并非如此,因此您可能需要更具体地说明您的结果。重要的是尽可能避免文字测试,而是按预期使用结果。例如:
assert_equal "this is amazing", "this is " + amazing_string_result
只要来自 amazing_string_result
的任何内容都可以附加到字符串并且结果与可接受的响应相匹配。
当您需要文字 true
或 false
而不是像 1
这样的真实值时,这通常会发挥作用:
assert_true some_method?(:value)
如果返回一个真实的但非文字的true
值,则契约(Contract)被破坏并且失败。
请记住,您可以拥有无限多的偏执狂。您确定您的值加起来正确吗?
assert_equal 6, 1 + 2 + 3
assert_equal 6, 6
assert_equal 6, '6'.to_i
assert_true true
在某些时候,您不再测试您的代码,而是在您执行此代码的编程语言或硬件上运行回归测试,如果您正在为 你的代码。
最好的单元测试:
- 通过清楚地描述对输入和输出的期望来演示应该如何使用代码。
- 识别并验证与所解决问题相关的任何和所有边界条件下的行为。
- 说明以必须明确禁止的不当方式使用代码时的故障模式。
- 避免展示代码无法正常工作的所有无限方式。
关于javascript - 在松散类型语言的单元测试中,是否应该检查方法的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878197/