我现在开始使用JUnit 5和Spring的测试。我有一个Rest,它包含控制器、服务和存储库,还有一些使用@value从application.properties获取属性的utils类。我不使用Spring中的“概要文件”,只是使用默认配置。
我的申请主要:
@EnableScheduling
@EnableDiscoveryClient
@ComponentScan
@SpringBootApplication
public class MyRestApiApplication {
public static void main(String[] args) {
SpringApplication.run(MyRestApiApplication.class, args);
}
}使用@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.
}主要考试课程:
@SpringBootTest
class MyRestApiApplicationTests {
@Test
void contextLoads() {
}
}我的测试类需要属性:
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");
}
}我的项目架构是:
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我在我的主Test类中尝试了"@TestPropertySource“和/或"@ActiveProfiles("test")”,但这没有奏效。也尝试使用"@RunWith(SpringRunner.class)“。
当我运行这个测试时,我的“秘密”值是"null",它应该是我的application.properties中的值。
我试着在我的JWTUtils jwtUtils中添加"@Autowired“,但结果是空的。@Autowired没有起作用。
发布于 2021-01-25 21:42:44
JWTUtilsTest不是弹簧引导测试。因此,没有弹簧引导魔法(比如注入配置值)JWTUtils的测试实例。要让spring施展它的魔力,您必须让spring创建它(例如,使用@Autowired注释,并使JWTUtilsTest成为弹簧引导测试。https://stackoverflow.com/questions/65890449
复制相似问题