0

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();
    }
  • AFAIK, this 'workaround' is the way to do this. And you don't need `@InjectMocks` if you don't have any other class dependencies. – Urosh T. Sep 05 '18 at 18:34
  • Inject only happens in spring managed beans. The instance used here is created by mockito not by spring and as such nothing will be injected. If you want to test the class set the properties yourself and write the test accordingly or use Spring to bootstrap the class instead of mockito. You also don't need the `@RuNWith` as it doesn't add anything here, not the `@InjectMocks` as you can simply create your own instance. – M. Deinum Sep 05 '18 at 18:34

1 Answers1

1

Instead of @InjectMocks, I suggest look into Spring Boot's @MockedBean annotation. Faking beans is much easier with it.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92