Issue
I have a class that uses an autowired properties object. These properties have some configuration required in order for my communications to work properly. In my unit tests I wrote a scenario in which communication should fail, by overriding the properties object in the class constructor as follows:
public class TokenRetriever{
@Autowired
private TokenRepository repository;
@Autowired
private Properties properties;
//custom constructor for me to override the properties
public TokenRetriever(Properties properties){
this.properties = properties;
}
private Token retrieveToken() {
Token token = null;
try {
//communication to an endpoint using properties
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return token;
}
public Token getAccessToken() throws NullAccessToken {
Token token;
token = repository.findTop1ByExpiresAtGreaterThanOrderByExpiresAtDesc(LocalDateTime.now());
if (token == null) token = this.retrieveToken();
if (token == null) throw new NullAccessToken("Could not retrieve any tokens");
return token;
}
}
And this is my unit test:
@Test
void ShouldNotRetrieveAToken() {
//this is the property i'm changing in order to force a failure
properties.setClientId("dummy");
tokenRetriever = new TokenRetriever(properties);
Exception exception = assertThrows(NullAccessToken.class,
() ->
tokenRetriever.getAccessToken()
);
String expectedMessage = "Could not retrieve any tokens";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
Which works just fine when I run the unit test. However, when I build the project this fails because the error is not thrown. I assume this is because the overriding is not working. I'm new to spring boot and junits, so this probably has to do with spring lifecycles. How can I accomplish the properties overide in order for my junit to pass?
Solution
Constructor injection Does injection only when the object create. if you want create another object with different property object you must use Setter-based dependency injection. there is setter-based injection documentation https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-setter-injection
Answered By - Alireza Hakimrabet
Answer Checked By - Gilberto Lyons (JavaFixing Admin)