MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

Integration & Functional Testing


Integration testing


Integration testing - Pros


Integration testing - Cons


Functional Tests


Functional Tests


Why Integration & Functional Tests?


Integration/Functional Test Design


Spring Integration testing


MockMVC


MockMVC - Autowired


MockMVC - Builders


Example MockMVC Builder test

def "add valid user"() {
   setup:
   def mockUserService = Mock(UserService)
   UserController userController = new UserController(userService: mockUserService)

   def user = new User(email: "foo", handle: "bar")
   def userBody = ObjectMapper.newInstance().writeValueAsString(user)

   def mockMvc = MockMvcBuilders.standaloneSetup(userController).build()

   when:
   mockMvc.perform(post("/users").content(userBody).contentType(MediaType.APPLICATION_JSON))
          .andExpect(status().isOk()).andDo(print())
          .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
          .andExpect(content().json(userBody, false))

   then:
   1 * mockUserService.addUser(user) >> user
 }

Spring Boot Functional Tests


SpringBootTest


TestRestTemplate


TestRestTemplate method types


Basic POST for entity Example

@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserFunctionalTests extends Specification {

  @Autowired
  private TestRestTemplate restTemplate

  def "/users - POST adds user"() {
      when:
      ResponseEntity<User> response = this.restTemplate.postForEntity("/users", new User(email: "foo@gmail.com", handle: "bar"), User.class)

      then:
      response.statusCodeValue == 200
      response.headers.getContentType() == MediaType.APPLICATION_JSON_UTF8
      User actual = response.body
      actual.email == "foo@gmail.com"
      actual.handle == "bar"
    }
}

Bootstrapping data


Example Boostrapped test

@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PostFunctionalTests extends Specification {
  @Autowired
  TestRestTemplate testRestTemplate

  @Autowired
  PostRespository postRespository

  @Autowired
  UserRepository userRepository

  def "get posts"() {
    setup:
    def user = new User(email: "foo@gmail.com", handle: "foo")
    userRepository.save(user)
    postRespository.save(new Post(user: user, message: "hello!"))

    when:
    ResponseEntity<Map> responseEntity = testRestTemplate.getForEntity("/posts", Map)

    then:
    responseEntity.statusCode == HttpStatus.OK
    Map actual = responseEntity.body

    actual.totalElements == 1

    def posts = actual.content as List
    posts.size() == 1

    def post = posts.get(0)
    post.message == "hello!"
    post.id == 1
  }
}