mock测试使用断言

受GeeCON会议期间@tkaczanowski演讲的启发,我决定仔细研究AssertJ库的自定义断言。

在我的“骰子”游戏中,我创建了一个“机会”,它是骰子的任何组合,其分数是所有骰子的总和。 这是相对简单的对象:

class Chance implements Scorable {@Overridepublic Score getScore(Collection<Dice> dice) {int sum = dice.stream().mapToInt(die -> die.getValue()).sum();return scoreBuilder(this).withValue(sum).withCombination(dice).build();}
}public interface Scorable {Score getScore(Collection<Dice> dice);
}

在我的测试中,我想看看如何计算不同骰子组合的分数。 我从简单开始(实际上只有一个):

public class ChanceTest {private Chance chance = new Chance();@Test@Parameterspublic void chance(Collection<Dice> rolled, int scoreValue) {// arrangeCollection<Dice> rolled = dice(1, 1, 3, 3, 3);// actScore score = chance.getScore(rolled);// assertassertThat(actualScore.getScorable()).isNotNull();assertThat(actualScore.getValue()).isEqualTo(expectedScoreValue);assertThat(actualScore.getReminder()).isEmpty();assertThat(actualScore.getCombination()).isEqualTo(rolled);}}

测试中验证了单个概念(得分对象)。 为了提高分数验证的可读性和可重用性,我将创建一个自定义断言。 我希望我的断言像其他任何AssertJ断言一样被使用,如下所示:

public class ChanceTest {private Chance chance = new Chance();@Testpublic void scoreIsSumOfAllDice() {Collection<Dice> rolled = dice(1, 1, 3, 3, 3);Score score = chance.getScore(rolled);ScoreAssertion.assertThat(score).hasValue(11).hasNoReminder().hasCombination(rolled);}
}

为了实现这一点,我需要创建一个从org.assertj.core.api.AbstractAssert扩展的ScoreAssertion类。 该类应具有公共静态工厂方法和所有必需的验证方法。 最后,实现可能如下图所示。

class ScoreAssertion extends AbstractAssert<ScoreAssertion, Score> {protected ScoreAssertion(Score actual) {super(actual, ScoreAssertion.class);}public static ScoreAssertion assertThat(Score actual) {return new ScoreAssertion(actual);}public ScoreAssertion hasEmptyReminder() {isNotNull();if (!actual.getReminder().isEmpty()) {failWithMessage("Reminder is not empty");}return this;}public ScoreAssertion hasValue(int scoreValue) {isNotNull();if (actual.getValue() != scoreValue) {failWithMessage("Expected score to be <%s>, but was <%s>", scoreValue, actual.getValue());}return this;}public ScoreAssertion hasCombination(Collection<Dice> expected) {Assertions.assertThat(actual.getCombination()).containsExactly(expected.toArray(new Dice[0]));return this;}
}

创建这样的断言的动机是拥有更多可读性和可重用性的代码。 但这要付出一些代价–需要创建更多代码。 在我的示例中,我知道我很快就会创建更多Scorables并且需要验证它们的评分算法,因此创建附加代码是合理的。 增益将可见。 例如,我创建了一个NumberInARow类,该类计算给定骰子组合中所有连续数字的分数。 分数是具有给定值的所有骰子的总和:

class NumberInARow implements Scorable {private final int number;public NumberInARow(int number) {this.number = number;}@Overridepublic Score getScore(Collection<Dice> dice) {Collection<Dice> combination = dice.stream().filter(value -> value.getValue() == number).collect(Collectors.toList());int scoreValue = combination.stream().mapToInt(value -> value.getValue()).sum();Collection<Dice> reminder = dice.stream().filter(value -> value.getValue() != number).collect(Collectors.toList());return Score.scoreBuilder(this).withValue(scoreValue).withReminder(reminder).withCombination(combination).build();}
}

我从连续检查两个5的测试开始,但是我已经错过了断言( hasReminder ,因此改进了ScoreAssertion 。 我继续用其他测试更改断言,直到获得可以在测试中使用的非常完善的DSL:

public class NumberInARowTest {@Testpublic void twoFivesInARow() {NumberInARow numberInARow = new NumberInARow(5);Collection<Dice> dice = dice(1, 2, 3, 4, 5, 5);Score score = numberInARow.getScore(dice);// static import ScoreAssertionassertThat(score).hasValue(10).hasCombination(dice(5, 5)).hasReminder(dice(1, 2, 3, 4));}@Testpublic void noNumbersInARow() {NumberInARow numberInARow = new NumberInARow(5);Collection<Dice> dice = dice(1, 2, 3);Score score = numberInARow.getScore(dice);assertThat(score).isZero().hasReminder(dice(1, 2, 3));}
}public class TwoPairsTest {@Testpublic void twoDistinctPairs() {TwoPairs twoPairs = new TwoPairs();Collection<Dice> dice = dice(2, 2, 3, 3, 1, 4);Score score = twoPairs.getScore(dice);assertThat(score).hasValue(10).hasCombination(dice(2, 2, 3, 3)).hasReminder(dice(1, 4));}
}

更改后的断言如下所示:

class ScoreAssertion extends AbstractAssert<ScoreAssertion, Score> {protected ScoreAssertion(Score actual) {super(actual, ScoreAssertion.class);}public static ScoreAssertion assertThat(Score actual) {return new ScoreAssertion(actual);}public ScoreAssertion isZero() {hasValue(Score.ZERO);hasNoCombination();return this;}public ScoreAssertion hasValue(int scoreValue) {isNotNull();if (actual.getValue() != scoreValue) {failWithMessage("Expected score to be <%s>, but was <%s>",scoreValue, actual.getValue());}return this;}public ScoreAssertion hasNoReminder() {isNotNull();if (!actual.getReminder().isEmpty()) {failWithMessage("Reminder is not empty");}return this;}public ScoreAssertion hasReminder(Collection<Dice> expected) {isNotNull();Assertions.assertThat(actual.getReminder()).containsExactly(expected.toArray(new Dice[0]));return this;}private ScoreAssertion hasNoCombination() {isNotNull();if (!actual.getCombination().isEmpty()) {failWithMessage("Combination is not empty");}return this;}public ScoreAssertion hasCombination(Collection<Dice> expected) {isNotNull();Assertions.assertThat(actual.getCombination()).containsExactly(expected.toArray(new Dice[0]));return this;}
}

我真的很喜欢自定义AssertJ断言的想法。 在某些情况下,它们将提高我的代码的可读性。 另一方面,我很确定不能在所有情况下都使用它们。 尤其是在那些可重用机会很小的地方。 在这种情况下,可以使用带有分组断言的私有方法。

你有什么意见?

资源资源

  • https://github.com/joel-costigliola/assertj-core/wiki/Creating-specific-assertions
  • @tkaczanowski的断言演变

翻译自: https://www.javacodegeeks.com/2014/05/spice-up-your-test-code-with-custom-assertions.html

mock测试使用断言

mock测试使用断言_使用自定义断言丰富测试代码相关推荐

  1. 互联网测试岗位分类_【科普】互联网测试岗位的工作日常

    近期公司新来了一批实习生,公司也组织了大量的人力物力对实习生的进行培训.不得不说,公司的确在朝"大公司"的方向发展,各项制度福利也在逐步完善.以前别说是实习生了,不管是社招还是校招 ...

  2. android中断言_我可以使用断言在Android设备上?

    I want to use the assert keyword in my android apps to destroy my app in some cases on the emulator, ...

  3. 开发转测试好转吗_月薪15K+的高级测试开发工程师基础面试题,你要来试试吗?...

    小编准备了三道测试开发题, 答对即有机会获得本期精选图书! 快来挑战吧!@所有人 本期图书介绍 本书从测试的角度,针对性地讲述了软件测试人员在软件测试和测试开发过程中需要掌握的知识点,以及需要达到的技 ...

  4. postman可以测试websocket吗_小海塔罗娱乐测试2021年可以脱单吗?

    默念问题 选择喜欢的牌 测试仅供娱乐 如需专业咨询 详细询问助理 A 权杖ace逆 2021年的你还是很努力的一年,努力的向下扎根,和爱情相比,你还是更想要面包.爱情对于现阶段的你来讲,是一个奢侈品. ...

  5. 使用C#为MSTest测试项目实现自定义断言

    前言 MSTest测试项目为我们实现了断言类Assert,用于报告代码行为的正确性,比如: var result = Calculator.Add(1,2); Assert.AreEqual(3, r ...

  6. assertj断言异常_编写自定义的AssertJ断言

    assertj断言异常 AssertJ是广泛使用的Hamcrest匹配器的替代匹配库. 实际上,对于我自己的项目,我已经更改为仅使用AssertJ-我只是发现流畅的界面和可扩展性非常吸引人. 您可以编 ...

  7. 使用自定义断言丰富测试代码

    受GeeCON会议期间@tkaczanowski演讲的启发,我决定仔细研究AssertJ库的自定义断言. 在我的"骰子"游戏中,我创建了一个"机会",它是骰子的 ...

  8. junit单元测试断言_简而言之,JUnit:单元测试断言

    junit单元测试断言 简而言之,本章涵盖了各种单元测试声明技术. 它详细说明了内置机制, Hamcrest匹配器和AssertJ断言的优缺点 . 正在进行的示例扩大了主题,并说明了如何创建和使用自定 ...

  9. web自动化断言_无需断言即可进行Web开发的自动化测试

    web自动化断言 图形用户界面(GUI)测试自动化已损坏. 回归测试不是测试: 它是软件行为的版本控制. 这是我的断言: 没有 断言的测试自动化效果更好! 在软件开发和测试自动化中,断言是一种检查计算 ...

最新文章

  1. java a 2_Java A* 算法(2)
  2. Linux下基于eclipse的arm开发环境的建立
  3. zbbix服务器搭建_zabbix服务器的搭建
  4. 随想录(在实践中学习kernel代码)
  5. POJ 1151 Atlantis 矩形面积求交/线段树扫描线
  6. 指导老师对计算机论文的评语,指导老师对论文的评语
  7. Java——正则表达式
  8. 小白学习cartopy气象画地图的第二天(中国区域,陆地温度分布图)
  9. java计算机毕业设计ssm拼团旅游系统element 前后端分离
  10. clustalw序列比对_序列比对之Clustalx与Clustalw使用指南
  11. PE头之IMAGE_FILE_HEADER解析
  12. 今日头条推广精品栏助力场景破壁
  13. 【Python百日基础系列】Day02-Python语法基础
  14. Web前端开发学习(一)
  15. linux中./和sh的区别
  16. 讯飞语音转文字_录音实时转文字就是如此简单 讯飞智能录音笔SR701评测
  17. 2009,新展望!站得稳雄得起!
  18. matlab关闭文本,matlab parpool 关闭
  19. 分享99个小清新PPT模板,总有一款适合您
  20. 经典量化选股方法——没有秘密的多因子

热门文章

  1. 【DP】I Will Like Matrix!
  2. [XSY] 宝藏(LCS,DP)
  3. SoundHound Inc. Programming Contest 2018[C. Ordinary Beauty]
  4. codeforces gym-101736 Dessert First Strategy 最小割
  5. codeforces gym-101741 Elevator 动态规划、单调队列
  6. Java制作VCARD
  7. Oracle入门(六)之用户操作
  8. 百度三轮面试回来,想和Java程序员分享一下。
  9. 上机不会做?在讲台上做做试试!
  10. el表达式与jstl的用法