2011-02-17 35 views
5

我想測試對象的特定字段是否與我指定的值匹配。在這種情況下,它是S3Bucket對象內的存儲桶名稱。至於我可以告訴大家,我需要爲此編寫自定義匹配:有沒有簡單的方法來匹配使用Hamcrest的字段?

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

任何人都可以把我指向類似的東西?在這種情況下,我想我已經解決了我的問題,但這不是我第一次希望得到更簡單的方法。

回答

9

或者,對於更安全的版本,還有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"))); 
    ... 
}}); 

兩個字符串參數的目的是讓讀得好的不匹配報告。

2

聽起來像你需要使用Matchers.hasProperty,例如,

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

或類似的東西。

1

沒有與LambdaJ這樣的一種巧妙的方法:

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