[英]NullPointerException when mocking repository JUnit
I have created a basic Rest API with a Controller, Service and Repository layer.我已经创建了一个带有控制器、服务和存储库层的基本 Rest API。 I am now trying to write a unit test for the Service layer method that finds product by the product id.我现在正在尝试为通过产品 ID 查找产品的服务层方法编写单元测试。 However, when I run the test it throws a NullPointerException in the line where I am trying to mock the repository findById() method.但是,当我运行测试时,它会在我尝试模拟存储库 findById() 方法的行中抛出 NullPointerException。
The getProductById() method in the service layer is as follows:服务层的getProductById()方法如下:
public Product getProductById(String id){ return productRepository.findById(id).orElse(null); }
My test class for the service layer:我的服务层测试类:
package com.product.Services;
import com.product.Entities.Product;
import com.product.Repositories.ProductRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
class ProductServiceTest {
@InjectMocks
ProductService productService;
@Mock
ProductRepository productRepository;
@Test
void getProductById() throws Exception {
Product product = new Product();
product.setId("001");
product.setName("TV");
product.setPrice(999.99);
when(productRepository.findById("001").orElse(null)).thenReturn(product);
assertEquals(product,productService.getProductById("001"));
}
}
The problem is that 2 different versions of JUnit are used here: org.junit.jupiter.api.Test
is from JUnit5, while org.junit.runner.RunWith
is from JUnit4.问题是这里使用了 2 个不同版本的 JUnit: org.junit.jupiter.api.Test
来自 JUnit5,而org.junit.runner.RunWith
来自 JUnit4。
RunWith
does not exist anymore in JUnit5. RunWith
在 JUnit5 中不再存在。
In this specific case, I would use JUnit4 - ie use the annotation org.junit.Test
(instead of org.junit.jupiter.api.Test
) to annotate your test.在这种特定情况下,我将使用 JUnit4 - 即使用注释org.junit.Test
(而不是org.junit.jupiter.api.Test
)来注释您的测试。
How to use Mockito with JUnit5 provides other valid solutions. 如何在 JUnit5 中使用 Mockito提供了其他有效的解决方案。
JUnit 5 使用@ExtendWith(SpringExtension.class)注解,你能不能改变@RunWith注解再试一次?
您应该模拟findById
调用,而不是与orElse
链接的表达式:
when(productRepository.findById("001")).thenReturn(product);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.