Spring Boot +在本地范围内使用UUID进行功能测试

时间:2018-11-21 10:53:10

标签: java unit-testing mockito

我要编写以下单元测试的功能:

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

该函数首先更新记录并将UUID放在记录上,然后基于该UUID标识符读取记录,现在我显然无法模拟UUID,但是当我运行以下单元时测试验证失败,因为实际上使用不同的findAllByIdentifier调用了方法UUID,然后我传入了,因为updateAndSelect在其内部创建了一个新的UUID

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

        }

0 个答案:

没有答案