尝试模拟存储库save()
方法,但是它总是返回null?
PS已通过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());
}
解
1. Mockito将equals
用于参数匹配,请尝试将ArgumentMatchers.any
用于save
方法。
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.或者,为模型实现equals
和hashCode
。
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;
}
}
参考文献
翻译自: https://mkyong.com/spring-boot/spring-mockito-unable-to-mock-save-method/