Я ищу, чтобы проверить, есть ли сущность, сохраненная в базе данных или нет? FindByEntityCode (String), который возвращает объект IdGenerator < /li>
< /ol>
Я издеваюсь над обеими службами, как это отражено в коде, но при попытке запустить тест, я получаю исключение из -за макета, я делаю что -то в основном неправильно неправильно неправильно, но не могу выяснить, что и почему, пожалуйста, любые предложения.@Mock
private InvestorRepository investorRepository;
@Mock
private InvestorRequestMapper investorRequestMapper;
@Mock
private InvestorResponseMapper investorResponseMapper;
@Mock
private IdGeneratorServiceImpl idGeneratorService;
@InjectMocks
private InvestorServiceImpl investorService;
IdGenerator idGenerator;
InvestorRequest investorRequest;
InvestorResponse investorResponse;
Investor investor;
idGenerator = new IdGenerator(customerId, "Test Generator", new BigInteger("10000"), new BigInteger("999999"), "Test", "New");
investorRequest = new InvestorRequest(type.toString(), adviserRequest, addressesRequest, individualRequest);
investorResponse = new InvestorResponse(customerId, customerId, type.toString(), adviserResponse, currency, status.toString(), addressesResponse, individualResponse, auditInfoResponse);
void testCreateInvestor_Success() {
// Given: Mock the behavior of investorRepository.save
when(investorRepository.save(investor)).thenReturn(investor);
when(idGeneratorService.findByEntityCode(anyString())).thenReturn(idGenerator);
when(idGenerator.getValue()).thenReturn(new BigInteger("10000"));
lenient().when(investorRequestMapper.apply(investorRequest)).thenReturn(investor);
lenient().when(investorResponseMapper.apply(investor)).thenReturn(investorResponse);
// When: Call the service method under test
InvestorResponse createdInvestor = investorService.addInvestor(investorRequest);
// Then: Assert the result and verify mock interactions
assertNotNull(createdInvestor);
assertEquals(firstName, createdInvestor.individual().firstName());
// Verify that save was called once with the correct investor object
verify(investorRepository, times(1)).save(investor);
}
< /code>
Код службы инвестора < /p>
@Override
public InvestorResponse addInvestor(InvestorRequest investorRequest) {
Investor investor = investorRequestMapper.apply(investorRequest);
BigInteger id = idGeneratorService.findByEntityCode(investorEntityCode).getValue();
investor.setCustomerId(hubwiseCode + EntityType.I + String.format("%08d", id));
Investor savedInvestor = investorRepository.save(investor);
return investorResponseMapper.apply(savedInvestor);
}
< /code>
Код службы идентификатора < /p>
@Service
@RequiredArgsConstructor
public class IdGeneratorServiceImpl implements IdGeneratorService {
private static final Logger logger = LoggerFactory.getLogger(IdGeneratorServiceImpl.class);
private final IdGeneratorRepository repository;
@Override
public IdGenerator findByEntityCode(String entityCode) {
IdGenerator idGenerator = null;
Optional optional = repository.findById(entityCode);
if(optional.isPresent()) {
idGenerator = optional.get();
logger.info("Successfully retrieved id generator : " + idGenerator.toString());
}
return idGenerator;
}
< /code>
ошибка /исключение < /p>
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Подробнее здесь: https://stackoverflow.com/questions/796 ... ked-servic