Snippets: Java: Spring: Testing

 20th August 2020 at 2:19pm

这个例子中,运行时会像你正常起一个 Spring 应用一样效果,会有 Bean 注入、Autowired 的值会被写入,等等。

注意 @ActiveProfiles("local") 必须在 @SpringBootTest 下面。不然不会加载配置文件。目录结构如下:

tsf-resource
    ├── pom.xml
    └── src
        ├── main
        │   ├── java.com.tencent.tsf.resource
        │   |   ├── controller
        │   |   ├── service
        │   └── resources
        │       └── application.yml
        └── test
            ├── java
            │   └── com.tencent.tsf.resource
            │       └── ApiHelperTest.java
            └── resources
                └── application-local.yml
package com.tencent.tsf.resource;

import com.tencent.tsf.TsfApplicationStarter;
import com.tencent.tsf.resource.config.ContainerConfigV2;
import com.tencent.tsf.resource.proxy.api.ApiHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TsfApplicationStarter.class)
@ActiveProfiles("local")
public class ApiHelperTest {
    private Logger logger = LoggerFactory.getLogger(ApiHelperTest.class);

    @Autowired
    private ContainerConfigV2 containerConfig;

    @Test
    public void testQueryParams() {
        ApiHelper helper = new ApiHelper(containerConfig.getMaster());
        logger.debug("{}", containerConfig.getMaster());
        logger.debug(helper.getUrl("/simple/test/path", null));
    }
}