I have a class which handles jwt creation:
public class JwtTokenHandler {
@Value("${jwtSecret}")
private String jwtSecret;
@Value("${jwtExpirationInMs}")
private int jwtExpirationInMs;
public String generateToken(String subject) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
return Jwts.builder()
.setSubject(subject)
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
}
And it takes jwtSecret and jwtExpirationInMs from properties file which lies in resources folder.
In my unit test i just want to test that this class works as expected and generates JWT token, the problem i face is that these two properties don't get injected when i run the test even though i have another properties file in test/resources folder.
I found that there is solution using ReflectionTestUtils.setField but it's more like a workaround.
My unit test looks like this:
@RunWith(SpringRunner.class)
public class JwtTokenProviderTest {
@InjectMocks
private JwtTokenProvider jwtTokenProvider;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGenerateToken() {
String result = jwtTokenProvider.generateToken("Test");
assertThat(result).isNotBlank();
}