Is there a simple way to match a field using Hamcrest?

后端 未结 3 1091
暗喜
暗喜 2020-12-10 08:32

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 t

相关标签:
3条回答
  • 2020-12-10 09:09

    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")))
      )
    }});
    
    0 讨论(0)
  • 2020-12-10 09:10

    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.

    0 讨论(0)
  • 2020-12-10 09:17

    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.

    0 讨论(0)
提交回复
热议问题