AndreyT
AndreyT

Reputation: 1499

How to mock String.equals in Groovy?

For testing purpose i need to override 'equals' method:

def any = [equals: { true }] as String
any == 'should be true'
// false

More detailed about problem:

class EmployeeEndpointSpec extends RestSpecification {

    void "test employee" () {
        when:
            get "/v1/employee", parameters
        then:
            expectedStatus.equals(response.statusCode)
            expectedJson.equals(response.json)
        where:
            parameters  << [
                [:],
                [id: 824633720833, style: "small"]
            ]
            expectedStatus << [
                HttpStatus.BAD_REQUEST,
                HttpStatus.OK
            ]
            expectedJson << [
                [errorCode: "badRequest"],
                [
                    id: 824633720833,
                    name: "Jimmy",
                    email: "[email protected]",
                    dateCreated:"2015-01-01T01:01:00.000", // this value should be ignored
                    lastUpdated: "2015-01-01T01:01:00.000" // and this
                ]
            ]
    }
}

lastUpdated and dateCreated may change in time, and i need somehow ignore them.

Upvotes: 2

Views: 528

Answers (2)

AndreyT
AndreyT

Reputation: 1499

The answer is:

String.metaClass.equals = { Object _ -> true }

Upvotes: 1

Opal
Opal

Reputation: 84804

If there's no need to compare mentioned fields - remove them:

class EmployeeEndpointSpec extends RestSpecification {

    void "test employee" () {
        when:
            get "/v1/employee", parameters
        then:
            expectedStatus.equals(response.statusCode)
            def json = response.json
            json.remove('dateCreated')
            json.remove('lastUpdated')
            expectedJson.equals(response.json)
        where:
            parameters  << [
                [:],
                [id: 824633720833, style: "small"]
            ]
            expectedStatus << [
                HttpStatus.BAD_REQUEST,
                HttpStatus.OK
            ]
            expectedJson << [
                [errorCode: "badRequest"],
                [
                    id: 824633720833,
                    name: "Jimmy",
                    email: "[email protected]",
                    dateCreated:"2015-01-01T01:01:00.000",
                    lastUpdated: "2015-01-01T01:01:00.000"
                ]
            ]
    }
}

I'd also separate testing negative and positive scenarios.

You can also test keySet() separately from testing keys values instead of comparing the whole map. This is the way I'd do that:

then:
def json = response.json
json.id == 824633720833
json.name == "Jimmy"
json.email == "[email protected]"
json.dateCreated.matches('<PATTERN>')
json.lastUpdated.matches('<PATTERN>')

In case You don't like the last two lines it can be replaced with:

json.keySet().contains('lastUpdated', 'dateCreated')

Upvotes: 1

Related Questions