我要编写以下单元测试的功能:
@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);
}