Unit Test =》 Coding refactore 反思

为了完成 80% 以上的行覆盖率, 我对代码 进行了哪些 重构? 

 

 

1. 组合 》继承  ,but 取决于 具体的应用场景

便于 mock 接口。 继承 通常 需要更多的依赖,but 组合 需要 更少的依赖  =》更多的依赖 意味着 更多的 mock

 

2. code 拆分为 更细的颗粒 : 增加 接口&实现。 对大段代码 进行 逻辑拆解

更小的mock 范围 =》 更少的依赖, 更容易 进行 分支mock

 

3. 发现bug =》 修复bug:

正常运行一段时间,很少发现bug。 but 仍可发现少数 漏网之鱼。

 

 

4. 目标 行覆盖率 =》 针对 继承 & 共享部分 ,只针对一个子类 进行测试即可。 因为是 行覆盖。 

随时check 行覆盖率 & 未覆盖的行。随时 check与目标的距离

 

 

5. add attribute to no logic class:  [ExcludeFromCodeCoverage]

like data model without any method 

 

 

6. prepare data from json file

 

            var filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)?.ToString() ?? "", "TestCase", tallixOriginalfilePath);
            var content = GetFileContent(filePath);
            return JsonSerializer.Deserialize<FileModel>(content, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

  

 

总结:

Unit test 是否可以容易进行,很大程度 取决于 code的 解耦程度  =》越精细化的UT, 越高的 UT覆盖率, 则 要求 越高水平的 code解耦。

posted @ 2022-12-08 08:39  PanPan003  阅读(16)  评论(0编辑  收藏  举报