bgarrels / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

New matcher to call a method on the object and match against its return value #165

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
You can easily assert the value of a method call on an object directly, for 
example:

    assertThat($obj->getId(), is(5));

However, you cannot do this in the context of another matcher such as 
arrayContaining() or hasEntry(). Say you want to assert that one of the objects 
in an array has an ID of 5.

Proposed syntax:

    [1] calling($methodName)[->with(...$params...)]->returns($matcher)

Example:

    assertThat($array, hasValue(calling('getId')->returns(5)));

I'm not sold on the syntax and wonder if any of these variations are better. 
Here we assert that calling add() with 1 and 2 return the value 3. Note that 
is() would be a synonym for returns() just as the function is() is a synonym 
for equalTo().

    [2] calling()->add(1, 2)->is(3)
    [3] calling('add', 1, 2)->is(3)

I like that [2] looks like the regular function call.

The [3] form shows that you could pass the parameters after the method name 
instead of using with(...). Both could be supported.

I'm also looking for a better name than calling(), perhaps whenCalled()?

Original issue reported on code.google.com by dharkn...@gmail.com on 14 Nov 2011 at 10:19

GoogleCodeExporter commented 9 years ago

Original comment by dharkn...@gmail.com on 14 Nov 2011 at 10:19