Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix BeNilMatcher not matching nil pointers #3

Merged
merged 2 commits into from
Oct 10, 2013
Merged

Conversation

pjvds
Copy link
Contributor

@pjvds pjvds commented Oct 10, 2013

I noticed that the BeNilMatcher returns false for pointers that point to a nil value. Here is a code example that fails:

var _ = Describe("BeNil", func() {
    It("should succeed when passing nil pointer", func() {
        var f *struct{}
        Ω(f).Should(BeNil())
    })

This is because actual is used as an interface{} type inside the BeNilMatcher. I have changed the implementation of it to, when the actual == nil check fails, it uses reflection to get check if actual is a pointer and if so, it check the element value for nil.

Here is the implementation:

func (matcher *BeNilMatcher) Match(actual interface{}) (success bool, message string, err error) {
    if actual == nil {
        return true, formatMessage(actual, "not to be nil"), nil
    } else {
        // When the value is not nil, check if it is a pointer
        // value and check if the element is nil.
        t := reflect.ValueOf(actual)
        if t.Kind() == reflect.Ptr {
            return t.IsNil(), formatMessage(actual, "to be nil"), nil
        }

        return false, formatMessage(actual, "to be nil"), nil
    }
}

@onsi
Copy link
Owner

onsi commented Oct 10, 2013

great catch. thanks for the PR!

onsi added a commit that referenced this pull request Oct 10, 2013
Fix BeNilMatcher not matching nil pointers
@onsi onsi merged commit eec9b13 into onsi:master Oct 10, 2013
onsi pushed a commit that referenced this pull request Mar 6, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants