mohit sharma mohit sharma - 3 months ago 22
Groovy Question

Declare Fields in groovy class Spock framework Unit test Case

I am make a Test Class for testing Employee Service , Everything is working fine , Except when i use a Field in other function it gets null.

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


Now what is want is to use

employeeService.remove(employee.getId);


for delete test function ,

Below is my code . Kindly provide some suggestion

I am new to 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;
}


}

Answer

Groovy doesn't have some kind of a global scope. You could add 'static' keyword.

static Employee response = null;