Spring Boot - 测试用例 - 不要加载所有组件

时间:2017-04-08 09:05:23

标签: java spring spring-boot spring-test

我想在Spring MVC中休息我的休息类

如果我运行以下代码(当项目很小但现在失败时运行正常)它会尝试加载我的应用程序中的所有不同组件。 这包括与外部系统交互并需要凭据才能连接的bean

PUT someindex
{
    "mappings": {"sometype":{"properties": {"titles":{"type": "nested"}}}}
}

POST someindex/sometype/0
{
   "titles": [
      { "title": "doc title", "depth": 0 },
      { "title": "sec title 1", "depth": 1 },
      { "title": "sec title 2", "depth": 1 }
   ]
}

POST someindex/sometype/1
{
   "titles": [
      { "title": "sec doc title", "depth": 0 }
   ]
}

GET someindex/sometype/_search
{
   "query": {
      "nested": {
         "path": "titles",
         "score_mode": "max",
         "query": {
            "function_score": {
               "query": {
                  "match": {
                     "titles.title": "sec"
                  }
               },
               "functions": [
                  {
                     "exp": {
                        "titles.depth": {
                           "origin": 0,
                           "scale": 1
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

如何告诉我的测试类不要加载我的应用程序的@Configuration或@Component类?

2 个答案:

答案 0 :(得分:3)

您不能在应用程序中创建其他类,而只能创建您感兴趣的类,请参阅15.6.1 Server-Side Tests - Setup Options

  

第二种是简单地手动创建一个控制器实例   加载Spring配置。而是基本的默认配置,   大致相当于MVC JavaConfig或MVC命名空间,   是自动创建的,可以自定义:

  public static int[] answer(int[] data, int n) {
    Map<Integer, Integer> counts = new HashMap<>();
    int elementsNeeded = 0;

    for (int i = 0; i < data.length; i++) {
      Integer currentCount = counts.get(data[i]);

      currentCount = currentCount == null ? 1 : ++currentCount;
      counts.put(data[i], currentCount);

      if (currentCount <= n + 1) {
        elementsNeeded += currentCount > n ? -n : 1;
      }
    }

    int[] resultArray = new int[elementsNeeded];
    int j = 0;

    for (int i = 0; i < data.length; i++) {
      if (counts.get(data[i]) <= n) {
        resultArray[j++] = data[i];
      }
    }

    return resultArray;
  }

答案 1 :(得分:1)

您需要使用@TestComponent@TestConfiguration来解决此问题,如Spring doc here中所述

相关问题