Why when I test ``` repository.delete()``` we do not need imitate repository.delete()?

Viewed 31

I have the following code:

@DeleteMapping(value = ["/library/books/{id}"])
fun deleteBook( @PathVariable("id") id: kotlin.Int): ResponseEntity<Unit> {
    return ResponseEntity(service.deleteBook(id), HttpStatus.valueOf(200))
}

override fun deleteBook(id: Int) {
    libraryRepository.findById(id).let {
        if(it == null){
            throw NotFoundException("Book with the given id not found")
        }
        libraryRepository.delete(it)
    }
}

@Test
fun `delete book and return 200`(){
    val library = Library(name = "testName", author = "testAuthor")
    `when`(libraryRepository.findById(1)).thenReturn(library)
    mvc.perform(MockMvcRequestBuilders.delete("/library/books/1"))
            .andExpect(MockMvcResultMatchers.status().isOk)
    verify(libraryRepository).delete(library)
}    

Here I am trying to write test, I suppose that it should fail, but it passed. I don't understand why my test is working, although I do not imitate when`(libraryRepository.delete(...)).

1 Answers

Take a look at your function:

override fun deleteBook(id: Int) {
    libraryRepository.findById(id).let { //1
        if(it == null){
            throw NotFoundException("Book with the given id not found")
        }
        libraryRepository.delete(it) //2
    }
}

Since you wrote:

`when`(libraryRepository.findById(1)).thenReturn(library)

method findById will return library instance, and then that instance will be passed to delete() method of libraryRepository. Since you didn't specify what should happen when this method is invoked, this line:

libraryRepository.delete(it)

Will return null.

Finally, you wrote this line of code in your test:

verify(libraryRepository).delete(library)

And since delete method of libraryRepository has been invoked, your test will pass.

Related