java - 如何比较 Java 中预期对象属性是动态的两个对象

标签 java compare cucumber comparator gherkin

我正在寻找一种基于以 Cucumber/Gherkin 格式编写的动态属性来比较 Java 中的对象的方法。

有没有人实现过类似的东西或者知道可以实现这一点的框架?

这是我正在尝试做的事情的示例:

cucumber .feature

Feature: Cucumber Feature 1

  Scenario: Test 1
    Given my micro-service is up and running
    When I submit something to my API
    Then I verify the response object looks like this:
      | property1 | value1 |
      | property3 | value3 |
      | property5 | value5 |

StepDefinitions.java

public class StepDefinitions {

    private ResponseObject storedResponseObject;

    @Given("^my micro-service is up and running$")
    public void given() throws Throwable {
        ...
    }

    @When("^I submit something to my API$")
    public void when() throws Throwable {
        storedResponseObject = postSomethingToAPI();
    }

    @Then("^I verify the response object looks like this:$")
    public void then(Map<String, String> gherkinMap) throws Throwable {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseObject expectedResponseObject = objectMapper.convertValue(gherkinMap, ResponseObject.class);
        ResponseObject actualResponseObject = storedResponseObject;
        Assert.assertEquals(expectedResponseObject, actualResponseObject);
    }
}

ResponseObject.java

public class ResponseObject {

    private String property1;
    private String property2;
    private String property3;
    private String property4;
    private String property5;

    public String getProperty1() {
        return property1;
    }

    public void setProperty1(String property1) {
        this.property1 = property1;
    }

    public String getProperty2() {
        return property2;
    }

    public void setProperty2(String property2) {
        this.property2 = property2;
    }

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String property3) {
        this.property3 = property3;
    }

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String property4) {
        this.property4 = property4;
    }

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String property5) {
        this.property5 = property5;
    }
}

注意 - Assert.assertEquals() 显然不起作用。

有什么想法吗?

谢谢

本:)

最佳答案

重写ResponseObject中的equals方法。在重写的方法中实现比较逻辑。

编辑

正如 @Wietlol 所注意到的,也覆盖 hashcode 方法。有关此内容的更多信息,您可以在这里阅读 In Java, why must equals() and hashCode() be consistent?

关于java - 如何比较 Java 中预期对象属性是动态的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45283202/

相关文章:

java - 我们如何获得跨度值

php - 比较值顺序不同的两个数组

ruby-on-rails - cucumber 测试停止

ruby-on-rails - 如何在带有 Selenium 的 Capybara 中使用 ruby​​-debug

syntax - Specflow 何时给出然后但是?

java - 如何在 glassfish 3.0 中配置 jdbc 领域

java - href 链接的 XPATH 不起作用。获取无效选择器 : It should be an element

java - 枚举反射

Python 列表比较和合并

python - 如果两个字典的键相等,则使用两个值执行操作并移动到新字典(python)