Home How to write Spock Unit Test by mocking the object and expecting some expected result
Reply: 0

How to write Spock Unit Test by mocking the object and expecting some expected result

user1240
1#
user1240 Published in May 25, 2018, 6:52 pm

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

}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.345078 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO