1、配置JBehave环境。
1)、添加JBehave依赖包,基本的只需要添加jbehave-core和Junit包就足够了。
2)、配置IntelliJ的JBehave插件,详情参见https://github.com/kumaraman21/IntelliJBehave/wiki
2、实现一个JBehave的Story基本过程
JBahave的测试用例主要由3部分组成,描述测试功能的story文件,story文件对应的Steps类和基于Junit的运行配置文件。Steps类是通过Anotation和正则匹配技术把story文件中的文本Step对应到Steps类中的方法,运行配置文件的主要作用是告诉junit去哪儿找story文件和Steps文件,把其配置在同一个Context中。实现一个story的基本过程如下:
1)、写Story
Meta:
@author liuxianning
@theme student
Narrative: In order to get a new student,as a teacher, I want to add a student into the Class
Scenario: Add a student into the class
Given There is a student
And his name is 'Lincoln'
And his age is '18'
And his hobby is 'basketball'
And his father's name is 'Mike'
And his mother's name is 'Mary'
And his brother's name is 'Luis'
When system add the student into class
Then we can get student 'Lincoln2' from class
2)、写Story对应的Steps类
public class StudentSteps {
private ClassRoom classRoom;
private Student student;
@Given("There is a student")
public void initStudent() {
student = new Student();
}
@Given("his name is '$name'")
public void setName(@Named("name")String name) {
student.setName(name);
}
@Given("his age is '$age'")
public void setAge(@Named("age")Integer age) {
student.setAge(age);
}
@Given("his hobby is '$hobby'")
public void setHobby(@Named("hobbu")String hobby) {
student.setHobby(hobby);
}
@Given("his father's name is '$fatherName'")
public void setFatherName(@Named("fatherName")String fatherName) {
student.setFatherName(fatherName);
}
@Given("his mother's name is '$motherName'")
public void setMotherName(@Named("motherName")String motherName) {
student.setMotherName(motherName);
}
@Given("his brother's name is '$brotherName'")
public void setBrotherName(@Named("brotherName")String brotherName) {
student.setBrotherName(brotherName);
}
@When("system add the student into class")
public void addStudentIntoClass(){
classRoom = new ClassRoom();
classRoom.addStudent(student);
}
@Then("we can get student '$studentName' from class")
public void checkGetStudent(@Named("studentName")String studentName){
assertThat(student, is(classRoom.getStudent(studentName)));
}
}
3)、配置运行环境
public class StudentStories extends JUnitStories {
public Configuration configuration() {
return new MostUsefulConfiguration().useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder().withCodeLocation(codeLocationFromClass(this.getClass())));
}
@Override
protected List<String> storyPaths() {
return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()),"**/*.story","");
}
}
4)、执行结果,执行StudentStories类,即可得到运行结果。
《未完待续》