Spring 使用 JUnit 5 测试属性

Spring Test Properties with JUnit 5

我现在开始使用 JUnit 5 和 Spring Boot 进行测试。 我有一个 Rest API,其中包含控制器、服务和存储库以及一些使用 @value 从我的 application.properties 获取属性的实用程序 classes。我没有使用 Spring 中的“配置文件”,只是使用默认配置。

我的主要应用程序:

@EnableScheduling
@EnableDiscoveryClient
@ComponentScan
@SpringBootApplication
public class MyRestApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyRestApiApplication.class, args);
    }

}

@value的class:

@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.
}

主要测试class:

@SpringBootTest
class MyRestApiApplicationTests {

    @Test
    void contextLoads() {
    }
}

我的测试class需要属性:

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

我在主测试中尝试了“@TestPropertySource”and/or“@ActiveProfiles("test")”class,但没有成功。还尝试使用“@RunWith(SpringRunner.class)”。

当我运行这个测试时,我的“秘密”值是“null”,这应该是我application.properties

中存在的值

我尝试将“@Autowired”放入我的 JWTUtils jwtUtils 但结果为空。 @Autowired 不起作用。

  1. JWTUtilsTest 不是 spring 引导测试。因此没有 spring 启动魔法(比如注入配置值)
  2. 您正在自己创建 JWTUtils 的测试实例。要让 spring 发挥它的魔力,您必须让 spring 创建它(例如,通过使用 @Autowired 注释并使 JWTUtilsTest 成为 spring 启动测试。