Home How to write Spock Unit Test by mocking the object and expecting some expected result
 I am trying to write unit test for addition of 2 numbers which is calling Service class add method() and there is one more class HelperAdd which is called from add() method Here in unit test case my expected result is different from what is hardcoded in unit test class, How to solve this. Am i doing something wrong in code. Unit Test Class-- class ControllerTest extends Specification { Service src HelperAdd hd def setup() { hd = Mock() src = new Service( hd: hd ) } def "Add 2 numbers"() { AddModel request = new AddModel() given: "input" request.setA(2) request.setB(3) when: src.add(request) then: 1 * hd.add(_) >> 2 expect:"4" } } Service class -- class Service { @Autowired HelperAdd hd @PostMapping(value="/getdocuments") def add(@RequestBody AddModel request) { int a = request.a int b = request.b int d = hd.add(a) int c = a+d return c } } HelperAdd class-- class HelperAdd { def add(int a) { int k = a+4 return k } } Model class -- @Canonical class AddModel { int a int b }