【发布时间】:2021-12-27 18:56:00
【问题描述】:
如何定义测试的“限制上下文”?
我之所以这么说是因为模拟,我的服务集成了许多其他库,例如:rabbit-mq、redis 等,以及来自某个类的实例。然后,我大部分时间都在编写测试代码,为服务创建“复杂”模拟以进行测试。
是否可能定义此限制?应该是一种可能的方式“不测试”这些“昂贵”的方法,而只测试“简单的相关方法”,即输入参数简单,如 sum(a, b)。
很明显,测试覆盖率越高越好,但是很多很多次编写一些有用的结果值得怀疑的测试。
当对定义好的方法使用 TDD 时,比如 sum(a,b),它非常有用,但是当这个方法将接收实例或使用来自另一个集成服务的实例时,mock 会收到大部分尝试,而不是“方法目标”。
想象一下这个服务/方法来测试:
class ClientService:
def ok_here_is_the_discount(self, some_args):
# Ok, receive the discount to thi signature, now is possible
# calcula the it, and response to the broker
self.calculate_user_discount_based_on_signature_type(some_args.discount_value)
def calculate_user_discount_based_on_signature_type(self, some_args):
# here will send the "result" to the broker
some_message_borker_publisher(
some_args.value - some_args.discount_signature
)
def request_the_signature_type_discount_in_another_service(self, some_args):
# Ok, I receive the client that has the signature type,
# now is need request what is the value to this signature
# in signature service
some_message_borker_publisher(
queue='siganture.service.what_discount_for_this_signature',
signature_type=some_args.client.singature_type
)
#Ok, this message goes to the broker, and the signature.service receive it
def method_that_receive_messages(self, some_args):
# Here we receives that want to calculate discount
# but just receive the client(dict/class/instance) with the signature type,
# we still dont know the value of theses discount, because when is responsible
# to manage the siganture, is the signature server
if some_args.message_type == 'please_calculate_discount':
self.request_the_signature_type_discount_in_another_service(some_args.client)
if some_args.message_type == 'message_from_signature_discount':
self.ok_here_is_the_discount(some_args.value)
1 - 它收到一条消息“please_calculate_discount”并调用该方法
self.request_the_signature_type_discount_in_another_service(some_args.client)
但它仍然没有折扣价值,因为这是签名服务。 (给经纪人的消息)
2 - 假设签名服务器响应“message_from_signature_discount”,则调用该方法:
self.ok_here_is_the_discount(some_args.value)
3 - 好的,方法 ok_here_is_the_discount 接收折扣和调用方法
calculate_user_discount_based_on_signature_type()
现在具有计算折扣的值并将这些值发送给经纪人。
了解这些测试 (TDD) 的复杂性吗?我需要测试模拟所有相关下一步操作的“method_that_receive_messages”,还是只测试相关方法,如“calculate_user_discount_based_on_signature_type”?
这种情况下最好用真正的broker可以测试一下吗?
【问题讨论】:
标签: python unit-testing mocking event-handling tdd