Abdu Muhammadal
Abdu Muhammadal

Reputation: 143

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;

And my test class is like this;

@ExtendWith(MockitoExtension.class)
class GServiceTest {

    @InjectMocks
    private GService service;

    @Mock
    private GRepository repository;

    @Mock
    private List<GameRule> rules;

Rules is okay but repository is not initialized and it is null. How can I initialize the repository?

Upvotes: 1

Views: 1961

Answers (1)

Gurkan İlleez
Gurkan İlleez

Reputation: 1583

You can set by using ReflectionTestUtils.setField(...) in Before Method;

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

Upvotes: 1

Related Questions