gpt4 book ai didi

java - 在groovy类Spock框架中声明字段单元测试用例

转载 作者:行者123 更新时间:2023-12-02 03:25:59 25 4
gpt4 key购买 nike

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

 // 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;
}

}

最佳答案

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

@Shared Employee 响应 = null

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

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

Static fields should only be used for constants. Otherwise shared fields are preferable, because their semantics with respect to sharing are more well-defined.

关于java - 在groovy类Spock框架中声明字段单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38889839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com