Is there a simple way to match a field using Hamcr

2019-01-18 15:36发布

I want to test whether a specific field of an object matches a value I specify. In this case, it's the bucket name inside an S3Bucket object. As far as I can tell, I need to write a custom matcher for this:

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")));
    ...
    }});

It would be nice if there were a simpler way to do this, something like:

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

Can anyone point me to something like that? I guess I've solved my problem already in this case, but this isn't the first time I've wished for a simpler way.

3条回答
唯我独甜
2楼-- · 2019-01-18 15:36

Sounds like you need to use Matchers.hasProperty, e.g.

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

Or something similar.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-18 15:51

Alternatively, for a more typesafe version, there's the FeatureMatcher. In this case, something like:

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

giving:

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

The purpose of the two string arguments is to make the mismatch report read well.

查看更多
不美不萌又怎样
4楼-- · 2019-01-18 15:54

There is a neat way of doing this with LambdaJ:

mockery.checking(new Expectations() {{
  one(query.s3).getObject(
    with(having(on(S3Bucket.class).getName(), is("bucket")))
  )
}});
查看更多
登录 后发表回答