如何在 JUnit 5 中模拟由 Autowired 和 RequiredArgsConstructor 组成的服务?

How to Mock service consisting both Autowired and RequiredArgsConstructor in JUnit 5?

@RequiredArgsConstructor
public class GService {

    @Autowired
    private GRepository repository;

    private final List<GRule> rules;

而我的测试class是这样的;

@ExtendWith(MockitoExtension.class)
class GServiceTest {

    @InjectMocks
    private GService service;

    @Mock
    private GRepository repository;

    @Mock
    private List<GameRule> rules;

规则没问题,但存储库未初始化且为空。如何初始化存储库?

可以在Before Method中使用ReflectionTestUtils.setField(...)进行设置;

ReflectionTestUtils.setField(service, "repository", Mockito.mock(GRepository.class));