Spring + Mockito Unable to mock save method?
By:Roy.LiuLast updated:2019-08-11
Try to mock a repository save() method, but it is always returning null?
P.S Tested with Spring Boot 2 + Spring Data JPA
@Test public void save_book_OK() throws Exception { Book newBook = new Book(1L, "Mockito Guide", "mkyong"); when(mockRepository.save(newBook)).thenReturn(newBook); mockMvc.perform(post("/books") .content("{json}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isCreated());
Solution
1. Mockito uses the equals for argument matching, try using ArgumentMatchers.any for the save method.
import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @Test public void save_book_OK() throws Exception { Book newBook = new Book(1L, "Mockito Guide", "mkyong"); when(mockRepository.save(any(Book.class))).thenReturn(newBook); //...
2. Alternatively, implements both equals and hashCode for the Model.
package com.mkyong; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.math.BigDecimal; @Entity public class Book { @Id @GeneratedValue private Long id; private String name; private String author; //... @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; if (id != null ? !id.equals(book.id) : book.id != null) return false; if (name != null ? !name.equals(book.name) : book.name != null) return false; return author != null ? author.equals(book.author) : book.author == null; @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (author != null ? author.hashCode() : 0); return result;
From:一号门
COMMENTS