 # spring test context重启定位

查看Spring TestContext cache 日志，运行测试时打开 cache DEBUG：

```shell
mvn -pl module-name "-Dtest=ClassA,ClassB" "-Dlogging.level.org.springframework.test.context.cache=DEBUG" test *> target/context-cache.log
```

Select-String -Path target\context-cache.log -Pattern "Spring test ApplicationContext cache statistics|Started .* in"

重点看 DefaultContextCache@xxx size = 1, hitCount = 120, missCount = 1

判断规则：

- missCount = 1：只创建过 1 个 Spring 上下文。
- missCount = 2 或更高：发生过新的上下文创建。
- size = 1：当前 cache 中只有 1 个上下文。
- size = 2：当前缓存了 2 套不同上下文。
- hitCount 增加：说明后续测试在复用已有上下文。

**定位具体重启发生的类**：

查询日志`Select-String -Path target\context-cache.log -Pattern "Starting .*Test|Started .*Test in|DefaultContextCache"`

判断方式：

1. 先看 missCount 从几变成几。
2. 找 missCount 增加附近，前后对应的测试类日志。
3. 如果看到第二个测试类也出现了：
  Starting XxxTest
  Started XxxTest in 40.123 seconds
基本就是它触发了新上下文。

例如：

```text
  Started ClassA in 55s
  DefaultContextCache size = 1, missCount = 1

  Starting ClassB
  Started ClassB in 42s
  DefaultContextCache size = 2, missCount = 2
```

那 ClassB 就没有复用 ClassA 的上下文。

常见有两种：
1. cache key 不同
     例如某个类多了 @MockitoSpyBean、@MockBean、@ActiveProfiles、@TestPropertySource、不同的 @SpringBootTest 参数，是 Spring 判断“这是另一套上下文”。
2. 上下文被主动标脏
     例如用了 @DirtiesContext，Spring 会把原上下文从 cache 移除，后续类不得不重建
