I'm starting now to use tests with JUnit 5 and Spring Boot. I have a Rest API with controllers, services and repositories and some utils classes that use @value
to get properties from my application.properties
. I'm not using "profiles" from Spring, just using the default configuration.
My Application Main:
@EnableScheduling
@EnableDiscoveryClient
@ComponentScan
@SpringBootApplication
public class MyRestApiApplication {
public static void main(String[] args) {
SpringApplication.run(MyRestApiApplication.class, args);
}
}
The class that uses @value
:
@Component
public class JWTUtils implements Serializable {
@Value("${jwt.validity}")
public String JWT_TOKEN_VALIDITY;
@Value("${jwt.secret}")
private String secret;
// There's no constructors in the class.
}
The Main Test class:
@SpringBootTest
class MyRestApiApplicationTests {
@Test
void contextLoads() {
}
}
My Test class that need the propertie:
class JWTUtilsTest {
JWTUtils jwtUtils;
@Test
void getUsernameFromToken() {
jwtUtils = new JWTUtils();
assertNotNull(jwtUtils.JWT_TOKEN_VALIDITY);
String username = jwtUtils.getUsernameFromToken("token-here");
assertNotNull(username);
assertEquals(username, "admin");
}
}
My project's architecture is:
main/
├── java/
│ ├── com.foo.controller/
│ ├── com.foo.model/
│ ├── com.foo.repository/
│ └── com.foo.service/
└── resources/
├── application.properties
├── banner.txt
test/
├── java/
│ ├── com.foo.controller/
│ ├── com.foo.model/
│ ├── com.foo.repository/
│ └── com.foo.service/
└── resources/
├── application-test.properties
I tried "@TestPropertySource" and/or "@ActiveProfiles("test")" in my Main Test class but that didn't worked. Also tried with "@RunWith(SpringRunner.class)".
When I run this test, my "secret" value is "null", which should be the value present in my application.properties
I tried putting "@Autowired" in my JWTUtils jwtUtils
but it came out null. The @Autowired didn't worked.
JWTUtilsTest
is not a spring boot test. Therefore no spring boot magic (like injecting configuration values)JWTUtils
yourself. To have spring cast its magic you have to let spring create it (eg by annotating with @Autowired
and making JWTUtilsTest
a spring boot test.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.