用机器人撰写关键字

时间:2019-11-15 16:14:48

标签: python robotframework atdd

让我们假设我有一个Python库来处理博客文章:

class BlogPost(object):
    def __init__(self):
        ...
    def create_a_blog_post(self):
        ...
    def add_category(self, category):
        ...
    def add_title(self, title):
        ...

我想要以下测试用例:

*** Test Cases ***
Create post with category
    Create a blog post with category "myCategory"
Create post with title
    Create a blog post with title "myTitle"
Create post with both
    Create a blog post with category "myCategory" and title "myTitle"

我是否应该为仅具有类别,仅具有标题以及两者都创建单独的用户关键字?还是有必要在关键字中添加任意数量的“修饰符”?

此外,如果我们必须将一个关键字的结果传递给另一个关键字,那么该如何创建这样的关键字:

*** Keywords ***
Create a blog post with category
    Create a blog post
    Add category  <-- How do I pass the blog post I just created to "Add category"

我故意从示例中省略了参数处理,因为这不是重点:)

1 个答案:

答案 0 :(得分:0)

我将创建一个名为“创建博客文章”的关键字,然后根据您的偏好传递关键字参数或键/值对。

您的测试将如下所示:

*** Test Cases ***
Create post with category
    Create a blog post  category  myCategory

Create post with title
    Create a blog post  title  myTitle

Create post with both
    Create a blog post
    ...  category  myCategory
    ...  title     myTitle

与关键字参数相比,我更喜欢键/值对,因为它使您可以将键和值对齐,如“两个”示例所示。如果您更喜欢关键字参数,它可能看起来像这样:

Create post with category
    Create a blog post  category=myCategory

Create post with title
    Create a blog post  title=myTitle

Create post with both
    Create a blog post  
    ...  category=myCategory  
    ...  title=myTitle

对于名称/值对,实现只需要对成对的参数进行迭代,或者对关键字args进行迭代。

  

此外,如果我们必须将一个关键字的结果传递给另一个关键字,那么该如何创建这样的关键字:

最简单的方法是将第一个关键字的结果保存在一个变量中,然后将该变量传递给下一个关键字。

Create another blog post
    ${post}=  Create a blog post
    Add blog post category  ${post}  thisCategory
    Add blog post category  ${post}  thatCategory

或者,一种更具编程性的方法是让Create a blog post返回带有添加类别的方法的对象,然后您可以使用Call Method在该对象上调用方法:

Create another blog post
    ${post}=  Create a blog post
    Call method  ${post}  add_category  thisCategory
    Call method  ${post}  add_category  thatCategory

    Add blog post category  ${post}  thisCategory
    Add blog post category  ${post}  thatCategory