【问题标题】:Is there a simple way to match a field using Hamcrest?有没有一种使用 Hamcrest 匹配字段的简单方法?
【发布时间】:2011-06-29 08:16:30
【问题描述】:

我想测试对象的特定字段是否与我指定的值匹配。在这种情况下,它是 S3Bucket 对象中的存储桶名称。据我所知,我需要为此编写一个自定义匹配器:

mockery.checking(new Expectations() {{
  one(query.s3).getObject(with(
      new BaseMatcher<S3Bucket>() {
        @Override
        public boolean matches(Object item) {
          if (item instanceof S3Bucket) {
            return ((S3Bucket)item).getName().equals("bucket");
          } else {
            return false;
          }
        }
        @Override
        public void describeTo(Description description) {
          description.appendText("Bucket name isn't \"bucket\"");
        }
      }), with(equal("key")));
    ...
    }});

如果有更简单的方法来做到这一点,那就太好了,比如:

mockery.checking(new Expectations() {{
  one(query.s3).getObject(
    with(equal(methodOf(S3Bucket.class).getName(), "bucket")),
    with(equal("key")));
    ...
}});

谁能给我指点类似的东西?我想我已经在这种情况下解决了我的问题,但这不是我第一次希望有更简单的方法。

【问题讨论】:

    标签: java unit-testing jmock hamcrest


    【解决方案1】:

    使用 LambdaJ 有一种巧妙的方法:

    mockery.checking(new Expectations() {{
      one(query.s3).getObject(
        with(having(on(S3Bucket.class).getName(), is("bucket")))
      )
    }});
    

    【讨论】:

      【解决方案2】:

      另外,对于更安全的版本,还有 FeatureMatcher。在这种情况下,类似于:

      private Matcher<S3Bucket> bucketName(final String expected) {
        return new FeatureMatcher<S3Bucket, String>(equalTo(expected), 
                                                    "bucket called", "name") {
           String featureValueOf(S3Bucket actual) {
             return actual.getName();
           }
        };
      }
      

      给予:

      mockery.checking(new Expectations() {{
        one(query.s3).getObject(with(bucketName("bucket")), with(equalTo("key")));
          ...
      }});
      

      两个字符串参数的目的是让不匹配报告读起来很好。

      【讨论】:

        【解决方案3】:

        听起来你需要使用Matchers.hasProperty,例如

        mockery.checking(new Expectations() {{
          one(query.s3).getObject(
            with(hasProperty("name", "bucket")),
            with(equal("key")));
            ...
        }});
        

        或类似的东西。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-01
          • 1970-01-01
          • 2017-07-16
          • 2016-09-29
          • 1970-01-01
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多