【发布时间】:2021-10-12 07:35:07
【问题描述】:
我有服务:
@Service
class UserService {
private final Map<AbstractSomeService, CustomEnum> someMap;
public UserService(List<AbstractSomeService> someService) {
someService.forEach(service -> someMap.put(service.getCustomEnum(), service));
}
public void logicExecution() {
//code
}
}
当我模拟如下:我得到 NullPointer:
@Mock
private SomeService someService; // Service which is extended of AbstractSomeService
@InjectMocks
private UserService userService = new UserService(Collection.singletonList(someService))
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testBrokenJunit() {
userService.logicExecution(); // NULL POINTER HERE (
}
一些服务:
@Service
public class SomeService extends AbstactSomeService() {
public CustomEnum getCustomEnum() {
return CustomEnum.BROKEN_JUNIT_TEST;
}
//logic here
}
堆栈跟踪非常简单:
java.lang.NullPointerException: Cannot invoke "getCustomEnum()" because "service" is null
没有构造函数初始化的StackTrace:
org.mockito.exceptions.misusing.InjectMocksException:
Cannot instantiate @InjectMocks field named 'UserService' of type '...'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Cannot invoke "java.util.List.forEach(java.util.function.Consumer)" because "someService" is null
at
Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.forEach(java.util.function.Consumer)" because "someService" is null
at UserService.<init>
附言
当我使用 UserService 的真实对象时,不是模拟一切都可以。
但它不适用于@InjectMocks
【问题讨论】:
-
尝试在用户参考中使用@MockBean
-
能否添加完整的测试代码?谢谢!
-
@JoãoDias 添加了“SomeService”的代码,并更新了代码
-
请同时发布堆栈跟踪,以便我们了解发生了什么。
-
我有一个类似的问题,当我注入的一个 Mocks 是 InjectMocks 的构造函数中的一个实现时。如果其他人有类似的问题,请尝试将实现更改为构造函数中的接口。