I have the following function that I want to write unit test for:
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyMessageServiceTests {
@Autowired
MyMessageService myMessageService;
@MockBean
MyMessageRepository myMessageRepository;
public List<MyMessage> updateAndSelect() {
UUID uuid = UUID.randomUUID();
String identifier = uuid.toString();
myMessageRepository.updateForSelect(identifier);
//a private method of the service that returns records based on identifier
return findAllByIdentifier(identifier);
}
}
The function first updates records and puts a UUID
against them and then reads the records based on that UUID
identifier, Now I cant Mock UUID
obviously but when I run the following unit test the verify fails because the method findAllByIdentifier
is actually called with a different UUID
then I am passing in, because updateAndSelect
creates a new UUID
within itself
@Test
public void testUpdateAndSelect(){
UUID uuid = UUID.randomUUID();
String identifier = uuid.toString();
when(myMessageRespository.findAllByIdentifier(identifier)).thenReturn(myMessages);
when(serviceUUID.randomUUID()).thenReturn(uuid);
myMessageService.updateAndSelect();
verify(myMessageRespository).findAllByIdentifier(identifier);
}