|
| 1 | +package ir.bigz.springbootreal.web |
| 2 | + |
| 3 | +import ir.bigz.springbootreal.controller.SampleController |
| 4 | +import ir.bigz.springbootreal.dao.User |
| 5 | +import ir.bigz.springbootreal.service.UserService |
| 6 | +import ir.bigz.springbootreal.service.UserServiceImpl |
| 7 | +import ir.bigz.springbootreal.viewmodel.UserModel |
| 8 | +import org.spockframework.spring.SpringBean |
| 9 | +import org.springframework.beans.factory.annotation.Autowired |
| 10 | +import org.springframework.boot.test.web.client.TestRestTemplate |
| 11 | +import org.springframework.context.ApplicationContext |
| 12 | +import org.springframework.http.HttpStatus |
| 13 | +import org.springframework.http.ResponseEntity |
| 14 | +import org.springframework.test.context.ActiveProfiles |
| 15 | +import org.springframework.test.context.ContextConfiguration |
| 16 | +import org.springframework.web.client.RestTemplate |
| 17 | +import spock.lang.Specification |
| 18 | +import spock.lang.Subject |
| 19 | +import spock.lang.Title |
| 20 | + |
| 21 | +@ContextConfiguration(classes = [SampleController.class, UserService.class, UserServiceImpl.class, UserModel.class, User.class]) |
| 22 | +@Title("sample spock test for testing project") |
| 23 | +@ActiveProfiles("test") |
| 24 | +class SampleApiTest extends Specification{ |
| 25 | + |
| 26 | +// @Autowired |
| 27 | +// ApplicationContext applicationContext |
| 28 | + |
| 29 | + @Autowired |
| 30 | + @Subject |
| 31 | + private SampleController sampleController |
| 32 | + |
| 33 | + @SpringBean |
| 34 | + UserService userService = Stub(UserService.class) |
| 35 | + |
| 36 | + private TestRestTemplate template |
| 37 | + |
| 38 | + void setup(){} |
| 39 | + |
| 40 | + def "if find user by id is ok"(){ |
| 41 | + |
| 42 | + given:"create mock userModel" |
| 43 | + UserModel user = generateUser() |
| 44 | + |
| 45 | + and:"define behavior of userService.getUser method" |
| 46 | + userService.getUser(_) >> user |
| 47 | + |
| 48 | + when:"call endpoint" |
| 49 | + def code = template.getForEntity("http://localhost:9090/api/v1//user/10", ResponseEntity<UserModel>.class as Class<Object>).statusCode |
| 50 | + |
| 51 | + then:"expected return result" |
| 52 | + code.value() == "200" |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + private static UserModel generateUser() { |
| 57 | + new UserModel( |
| 58 | + id: UUID.randomUUID(), |
| 59 | + userName: "sample", |
| 60 | + firstName: "first", |
| 61 | + lastName: "last", |
| 62 | + nationalCode: '0014713225', |
| 63 | + mobile: '09388773155', |
| 64 | + gender: "man" |
| 65 | + ) |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments