ITeye博客

Spock Mock Cheatsheet

jusi · 2014-12-10 16:29 · test · 编程语言 · Markdown

Spock Mock Cheatsheet

Craig Atkinson

Executable examples at github.com/craigatk/spockmockcheatsheet

 

Creating mocks

UserService userService = Mock()

def userService = Mock(UserService)

 

Argument matching

userService.createUser(email, name) >> user

userService.sendWelcomeEmail({ User u >

u.email == email && u.name == name })

userService.createUser(_ as String, _ as String) >> user

userService.createUser(_, _) >> user

 

Verify method call number

1 * userService.createUser(email, name) >> user

1 * userService.sendWelcomeEmail(user)

0 * _

 

Use method arguments in return value

userService.createUser(email, name) >> { String e, String n >

new User(email: e, name: n)

}

 

Throw exception from method

userService.sendWelcomeEmail(user) >> { throw new IllegalStateException() }

 

Mock definition outside of test spec

interaction {

userCreationMocks(email, name)

}

 

private void userCreationMocks(String email, String name) {

User user = new User()

1 * userService.createUser(email, name) >> user

1 * userService.sendWelcomeEmail(user)

}

 

1 * subscriber.receive("hello")     // an argument that is equal to the String "hello"
1 * subscriber.receive(!"hello")    // an argument that is unequal to the String "hello"
1 * subscriber.receive()            // the empty argument list (would never match in our example)
1 * subscriber.receive(_)           // any single argument (including null)
1 * subscriber.receive(*_)          // any argument list (including the empty argument list)
1 * subscriber.receive(!null)       // any non-null argument
1 * subscriber.receive(_ as String) // any non-null argument that is-a String
1 * subscriber.receive({ it.size() > 3 }) // an argument that satisfies the given predicate
                                          // (here: message length is greater than 3)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。