首页 > 解决方案 > 具有有效和无效输入的黄瓜表

问题描述

我有一种有效的测试:

Feature: TestAddition

  Scenario Outline: "Addition"
    Given A is <A> and B is <B>
    Then A + B is <result>

    Examples: 
      | A      | B    | result |
      |      3 |    4 |      7 |
      |      2 |    5 |      7 |
      |      1 |    4 |      5 |

这就是胶水代码:

package featuresAdditions;

import org.junit.Assert;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import math.AdditionEngine;

public class step {

    private AdditionEngine testAdditionEngine;
    private double resultAddition;

    @Given("^A is (\\d+) and B is (\\d+)$")
    public void addition(int arg1, int arg2) throws Throwable {
        testAdditionEngine = new AdditionEngine();
        resultAddition = testAdditionEngine.calculateAdditionAmount(arg1, arg2);
        }


    @Then("^A + B is (.)$")
    public void addition(double arg1) throws Throwable {
        Assert.assertEquals(arg1, resultAddition, 0.01);
    }      
}

但是我想知道如何创建一个无效的表示例 [where ?? 表示我不知道在下表中放什么]

Examples: 
  | A      | B    | result |
  | "é3-3" |    5 |     ?? |
  | "é3-3" | "aB" |     ?? |

这应该给出一个java.lang.NumberFormatException

在纯 jUnit 中,我会做类似下面的代码,它就像 [with @Test(expected = NumberFormatException.class)] 的魅力。但是,我必须使用 Cucumber ...有人可以告诉我如何使用 Cucubmer 进行这样的测试吗?

public class test {
    AdditionEngine testAdditionEngine = new AdditionEngine();
    @Test(expected = NumberFormatException.class)
    public void test() {
        testAdditionEngine.calculateAdditionAmount("é3-3", 5);
    }
}

标签: cucumbernumberformatexceptioninvalid-argument

解决方案


  Scenario Outline: "Invalid Addition"
    Given A is <A> and B is <B>
    Then A + B is <result>

    Examples: 
      | A      | B    | result                          |
      | "é3-3" | 5    | java.lang.NumberFormatException |
      | "é3-3" | "aB" | java.lang.NumberFormatException |

更改 stepdefinition 以将 aString作为参数而不是Integer.

private Exception excep;

    @Given("^A is (.*?) and B is (.*?)$")
    public void addValid(String arg1, String arg2) {

        try {
            testAdditionEngine = new AdditionEngine();
            testAdditionEngine.calculateAdditionAmount(arg1, arg2);
        } catch (NumberFormatException e) {
            excep = e;
        }
    };

    @Then("^A \\+ B is (.*?)$")
    public void validResult(String arg1){
        assertEquals(arg1, excep.getClass().getName());
    };

如果您在 Cucumber 2 及更高版本上,您将收到一条模棱两可的步骤消息。这是因为有效的方案大纲将匹配整数和字符串步骤定义。更改任一方案语句。

在此处输入图像描述

在此处输入图像描述


推荐阅读