简体   繁体   English

JUnit 5 RefreshToken 测试 Mockito

[英]JUnit 5 test Mockito for RefreshToken

Below is the code下面是代码

@Service public class RefreshTokenServiceImpl implements RefreshTokenService { @Service public class RefreshTokenServiceImpl 实现 RefreshTokenService {

@Autowired
private RefreshTokenRepository refreshTokenRepository;

@Override

public RefreshToken generateRefreshToken() {

RefreshTokenEntity tokenEntity = new RefreshTokenEntity();

tokenEntity.setToken(UUID.randomUUID().toString());

tokenEntity.setCreatedDate(Instant.now());


tokenEntity = refreshTokenRepository.save(tokenEntity);

return RefreshTokenBeanMapper.REFRESH_TOKEN_BEAN_MAPPER.refreshTokenEntityToModel(tokenEntity);
}

RefreshToken刷新令牌

public class RefreshToken {


private Long id;


private String token;

private Instant createdDate;
}

RefreshTokenBeanMapper RefreshTokenBeanMapper

@Mapper

public interface RefreshTokenBeanMapper {

RefreshTokenBeanMapper REFRESH_TOKEN_BEAN_MAPPER = Mappers.getMapper(RefreshTokenBeanMapper.class);

RefreshToken refreshTokenEntityToModel(RefreshTokenEntity refreshTokenEntity);

}

Trying to write a suitable JUnit 5 Mockito test尝试写一个合适的 JUnit 5 Mockito 测试

As i understand, you need always generate the only one UUID and Date for yours token testing.据我了解,您始终需要为您的令牌测试生成唯一的 UUID 和日期。 For this, you can use experimental mockito-inline which contains functionality for static methods.为此,您可以使用实验性 mockito-inline,它包含 static 方法的功能。

I guess you need something like this:我想你需要这样的东西:

UUID testUUID = UUID.randomUUID();
Instant n = Instant.now();
    try {
      MockedStatic<UUID> uuid = Mockito.mockStatic(UUID.class)
      uuid.when(UUID::randomUUID).thenReturn(testUUID);
      MockedStatic<Instant> inst = Mockito.mockStatic(Instant.class)
      inst.when(Instant::now).thenReturn(n);
      ...
}
    ...

https://www.baeldung.com/mockito-mock-static-methods https://www.baeldung.com/mockito-mock-static-methods

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM