Spring + Mockito –无法模拟保存方法?

在Spring Boot 2 + Spring Data JPA环境中遇到使用Mockito模拟存储库方法返回null的问题。解决方案包括正确使用Mockito的参数匹配,以及考虑为模型实现equals和hashCode方法。
摘要由CSDN通过智能技术生成

尝试模拟存储库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.或者,为模型实现equalshashCode

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值