如何在测试中创建测试对象?
我正在为付款流程创建单元测试。大约需要编写 20 个单元测试 - 一些正面案例和一些负面案例。
例子:
payment_screen=PaymentScreen()
我的想法很少。
首先 - 创建一个具有给定属性的 Payer 对象:
payer=Payer(last_name,country_code)
country_code 很重要,因为系统不允许将项目发送到其他国家
第二个
payer=Payer.return_correct_payer()
类似:
class Payer:
@staticmethod
def return_correct_payer():
payer=Payer()
payer.country_code='US'
payer.last_name='Smith'
并且在两个选项中
payment_screen.fill_payer_data(payer)
还有另一个概念:
在 payment_screen 中只需创建两个方法:
fill_payer_data_with_correct_data()
和
fill_payer_data_with_uncorrect_data()
哪一个最好?或者也许您有另一个想法(我确信您有)
编辑
感谢您的回复,但这不是我需要的。 我只是不想在每个测试用例中创建具有给定属性的对象 Pax。
我有 20 个测试用例,所以现在我必须写 20 次:
payer=Payer('Smith','US')
我不想重复我的代码
I'm creating unittests to a payment process. There is about 20 unit unittests to write -some positives cases and some negatives.
example:
payment_screen=PaymentScreen()
and there I few conceptions.
First - create a Payer object with giving attributes:
payer=Payer(last_name,country_code)
country_code is important, because system doesn't allow to sending items to other countries
Second
payer=Payer.return_correct_payer()
something like:
class Payer:
@staticmethod
def return_correct_payer():
payer=Payer()
payer.country_code='US'
payer.last_name='Smith'
and in both options
payment_screen.fill_payer_data(payer)
And an another conception:
in payment_screen just create two methods:
fill_payer_data_with_correct_data()
and
fill_payer_data_with_uncorrect_data()
Which one is the best? Or maybe you have another idea(I'm sure that you have)
EDIT
Thanks for your replies, but it's not what I need.
I just don't want create object Pax in every test case with giving attributes.
I have 20 test cases so now I must write 20 times :
payer=Payer('Smith','US')
I don't want duplicate my code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您正在寻找某种模拟框架。然后,当您测试
PaymentScreen
时,您可以模拟Payer
。有关 Python 模拟框架的更多信息,请参阅此处:您最喜欢的 Python 模拟库是什么?。Maybe what you are looking for is some kind of mocking framework. Then when you test
PaymentScreen
, you can mock outPayer
. For more about mocking frameworks for python look here: What is your favorite Python mocking library?.嘿。
也许用模拟来回答是您首先需要的,但我想展示如何在测试中创建对象。
因此,如果我需要一个具有给定参数的对象,我会使用 BuilderPattern(实际上是从 GOF 修改的 BuilderPattern),它看起来像这样:
然后我用以下方式启动对象:
然后我用它做我需要的事情。
PS 抱歉,代码不是 python 语法...但你应该得到它
Hey.
Probably answer with mocks is what you need in the first place, but I want to show how I create objects in my tests.
So if I need a object with given parameters I use BuilderPattern (actually modified BuilderPattern from GOF), which looks like this:
Then I initiate object with:
and then I do with it, what I need.
P.S. Sorry for code not being python syntax... but you should get it