【问题标题】:custom error message for assertThat() in junit?junit 中 assertThat() 的自定义错误消息?
【发布时间】:2014-04-30 21:58:49
【问题描述】:

我想知道 assertThat() 是否可以添加自定义错误消息?

例如在这个:

assertThat(file.exists(), is(equalTo(true)));

我想添加一些自定义消息,说明哪个文件名不存在

【问题讨论】:

    标签: java junit


    【解决方案1】:

    我更喜欢以下内容,以避免读者认为您希望断言文件名不存在..!

    assertThat("File name should exist", file.exists(), is(equalTo(true)));
    

    【讨论】:

      【解决方案2】:

      使用重载的assertThat方法

      assertThat("File name doesn't exist", file.exists(), is(equalTo(true)));
      

      【讨论】:

      • 注意可读性!当您阅读它时:“断言该文件名不存在......”......这与您实际测试的相反!
      【解决方案3】:

      我更喜欢这个,因为可以把它读成一句话:“assert that file 'myFile' exists: myFile exists is true”

      assertThat("File '" + myFile + "' exists", myFile.exists(), is(true));
      

      当它失败时,它也会获得包含所有必要信息的可读消息:

      java.lang.AssertionError: File '/blah' exists
      Expected: is <true>
           but: was <false>
      

      【讨论】:

        【解决方案4】:

        您可能只想使用带有 2 个参数的 assertTrue() 方法:

        Assert.assertTrue("File "+file.getAbsoluePath()+"does not exist", file.exists());
        

        【讨论】:

          【解决方案5】:

          我用这个方法:

          Throwable thrown = catchThrowable(() -> myTestedObject.funtion());
          assertThat("Error Message", thrown, isInstanceOf(MyException.class));
          

          【讨论】:

            猜你喜欢
            • 2018-08-12
            • 2014-12-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-03
            • 1970-01-01
            相关资源
            最近更新 更多