有没有一种简单的方法可以使用 Hamcrest 来匹配字段?
我想测试对象的特定字段是否与我指定的值匹配。在本例中,它是 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")));
...
}});
任何人都可以向我指出类似的事情吗?我想在这种情况下我已经解决了我的问题,但这并不是我第一次希望有一种更简单的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者,对于类型更安全的版本,可以使用FeatureMatcher。在本例中,类似于:
给出:
两个字符串参数的目的是使不匹配报告易于阅读。
Alternatively, for a more typesafe version, there's the FeatureMatcher. In this case, something like:
giving:
The purpose of the two string arguments is to make the mismatch report read well.
听起来你需要使用
Matchers.hasProperty
,例如或类似的东西。
Sounds like you need to use
Matchers.hasProperty
, e.g.Or something similar.
使用 LambdaJ 有一种巧妙的方法可以做到这一点:
There is a neat way of doing this with LambdaJ: