Spring + Mockito Unable to mock save method?

摘要: Try to mock a repository save() method, but it is always returning null?

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;

上一篇: Spring Test How to test a JSON Array in jsonPath
下一篇: Java – Convert Integer to String
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号