【问题标题】:Declare Fields in groovy class Spock framework Unit test Case在 groovy 类 Spock 框架单元测试用例中声明字段
【发布时间】:2016-08-11 07:22:25
【问题描述】:

我正在创建一个测试类来测试员工服务,一切正常,除非我在其他函数中使用字段,否则它会变为空。

 // field
 Employee employee;
 // this will be assigned to return of below 
 employee= employeeService.create(emp);
 // this(employee) gets null

现在想要的是使用

         employeeService.remove(employee.getId);

用于删除测试功能,

下面是我的代码。请提供一些建议

我是 groovy 的新手。

package services.employee
import spock.lang.Specification
@ContextConfiguration(loader =          SpringApplicationContextLoader.class,classes = Application.class)
class EmployeeSpec extends  Specification{

  @Autowired
  EmployeeService employeeService;

Employee response = null;
 def "Check if Employee exists"(){
    setup:
    long empid = 43;

    when:
    empid > 0

    then:
    employeeService.getEmployee(empid);
 }

def "Find all Employee"(){
    setup:

    when:
    def res = employeeService.getAllEmployees();

    then:
    res.size()>0;
}

def "Insert a New Employee"(){

    setup:
    Employee employee = new Employee();
    employee.setName("Ajit Singh");
    employee.setCity("Delhi");
    employee.setAge(34);

    when:
    response = employeeService.createEmployee(employee);

    then:
    response.getName().equals("Ajit Singh");

}

def "Updating an Employee"(){


}

def "delete an Employee"(){
    setup:
    if (response.equals(null))
        println("Object is null");

      when:
      employeeService.removeEmployee(response.empID)

     then:
     def res = employeeService.find(response.empID);
     res == null;
}

}

【问题讨论】:

    标签: java spring unit-testing groovy spock


    【解决方案1】:

    虽然 Ivans 回答上述问题有效,但在 Spock 中执行此操作的正确方法是使用 @Shared 注释:

    @Shared Employee response = null

    (见https://spockframework.github.io/spock/docs/1.1-rc-1/all_in_one.html#_fields

    引用文档为什么这是正确的方法:

    静态字段只能用于常量。否则共享字段更可取,因为它们在共享方面的语义更明确。

    【讨论】:

    • 嗯,你的回答很有说服力
    【解决方案2】:

    是的,您可以使用@Shared 标签,使用该标签声明的变量可能是 java 或 C 中的全局变量。 我不知道您的“createEmployee”函数返回什么,但这在 groovy 中不是问题,因为您可以使用“def”类型而不是所有类型。
    所以,您只需添加 @Shared def response = null

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多