1

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);

        }
Toseef Zafar
  • 1,601
  • 4
  • 28
  • 46
  • You can use any(String.class) instand of passing uuid.toString(); – Ravi Sapariya Nov 21 '18 at 10:57
  • Thanks @RaviSapariya just thinking how would that work because the verify will complain if the value in the side function is not identical in the service function and the unit test – Toseef Zafar Nov 21 '18 at 10:59
  • 1
    As this is a Spring Boot test you have other options than pure mocking, i.e. SpringFramework provides an `IdGeneartor` that you can implement to provide a known UUID each time plus impls for generating UUIDs as standard e.g. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/IdGenerator.html – Darren Forsythe Nov 21 '18 at 13:10
  • @DarrenForsythe thats the answer...works like a charm! please put that in answer and I will mark it. – Toseef Zafar Nov 21 '18 at 13:20

0 Answers0