Mais conteúdo relacionado Semelhante a Spock:願你的測試長長久久、生生不息 (20) Spock:願你的測試長長久久、生生不息8. Java
class Person {
String firstName
String lastName
}
public class Person {
private String firstName;
private String lastName;
public Person(){}
public Person(Map<String, String> args){
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Groovy
13. 1. JDK 6 +
2. Groovy 2.1+
3. Gradle 1.0 +
4. Your favorite IDE
Prerequisite
14. Setup
// build.gradle
apply plugin: 'java'
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.3'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
}
17. • 在Spock中,待測系統 (system under test;
SUT) 的行為是由規格 (specification) 所定
義的。
• 我們透過定義Specification的子類別來
完成SUT行為規格的制定。
• 即JUnit中的test class。
Specification
26. • setup: or given:
• expect:
• when:
• then:
• where:
• cleanup:
• and:
Blocks in Feature Methods
33. What is this feature?
Given a stack and an
element,
when we push the
element on the stack,
then the size of the
stack should be one
and the peeked
element should be
the one we pushed
on.
34. • Setup
• Create Specification
• Define feature methods
• Run and show report
Demo
52. • 18:15 Release前發現還有一個bug
• 18:20 修好了!
• 18:21 發deploy request,打電話問老婆晚上要吃
什麼。
• 18:25 (搭電梯中)
QA來電:那個OOXX怎麼沒出來啊?
• ………(不知過了多久)
• 21: 35 「老婆,還有飯嗎?」
應該蠻常見的…
54. • 確認程式各單元 (units) 行為是否符合需求。
• 測試時SUT需與外界完全獨立。
– 以test doubles替換實際相依元件。
• 數量多、執行快。
• 結構單純。
– Arrange-Act-Assert, aka,
Given-When-Then
Unit Tests
69. Additional Dependencies
// build.gradle
apply plugin: 'java'
apply plugin: 'groovy'
repositories {
mavenCentral() ""
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.3'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0‘
testRuntime 'cglib:cglib-nodep:2.2.2'
testRuntime 'org.objenesis:objenesis:1.2'
}
70. TargetClass mockTarget = Mock()
def mockTarget = Mock(TargetClass)
1 * mockTarget.receive("msg")
(1..3) * mockTarget.receive(_)
(1.._) * mockTarget.receive(_ as String)
Mocking
71. class PublisherSpec extends Specification {
Publisher publisher = new Publisher()
Subscriber subscriber = Mock()
Subscriber subscriber2 = Mock()
def setup() {
publisher.subscribers << subscriber
publisher.subscribers << subscriber2
}
def "should send messages to all subscribers"() {
when:
publisher.send("hello")
then:
1 * subscriber.receive("hello")
1 * subscriber2.receive("hello")
}
}
Verify Interactions
76. • Homepage http://spockframework.org
• Documentation http://docs.spockframework.org
• Spock Web console
http://webconsole.spockframework.org
• Source code http://github.spockframework.org/spock
• Spock example
http://github.spockframework.org/spock-example
References