Spring + Mockito – Unable to mock save method?
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;
}
}
Hi, Here I am sharing my issue employeeDAO.findById(id).orElseThrow(() -> new RuntimeException()); the above one is the CurdRepository query I am mocking the the object using mockito Mockito.when(employeeDAO.findById(id).orElseThrow(() -> new RuntimeException())) .thenReturn(Optional.of(ce).orElseThrow(() -> new RuntimeException())); but is java.lang.RuntimeException at revelar.global.satta.services.EmployeeServiceTest.lambda$0(EmployeeServiceTest.java:68) at java.base/java.util.Optional.orElseThrow(Optional.java:408) at revelar.global.satta.services.EmployeeServiceTest.findById(EmployeeServiceTest.java:68) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)… Read more »