【问题标题】:Why 'assert' is not failing in junit test为什么'assert'在junit测试中没有失败
【发布时间】:2016-04-01 23:07:05
【问题描述】:

我在代码中使用了“断言”。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Puppy.class })
public class PuppyTest {

    @Test
    public void testCreatePuppy() {
        // Mocking
        Human human = Mockito.mock(Human.class);
        Puppy puppy = Puppy.createPuppy("Gatsby", human);
        assert(null!=puppy);
        assert("Gatsby1".equals(puppy.getName()));
        assert false;   //This should fail anyway
    }

  .....

} 

但是,即使对于虚假条件,断言也不会失败。 如果我使用 Assert 类方法,它会按预期工作。

  @Test
    public void testCreatePuppy() {
        // Mocking
        Human human = Mockito.mock(Human.class);
        Puppy puppy = Puppy.createPuppy("Gatsby", human);
        Assert.assertNotNull(puppy);
        Assert.assertEquals("Gatsby1",puppy.getName());
  }

我们不能在 Junit 测试用例中使用断言吗?

更新:

我通过将 -ea 作为 vm 参数传递来启用断言。它奏效了。 :)

【问题讨论】:

    标签: java unit-testing junit mockito powermock


    【解决方案1】:

    要使 java 断言正常工作,您需要使用 -ea 标志运行应用程序/测试。尝试使用 -ea 标志。其中Assert 是特定于 JUnit 的,并且断言语句与 java 断言无关。

    【讨论】:

    • 顺便说一句,很多人(包括我在内)说你永远不应该在测试中使用简单的断言(与 Assert 类方法相反)。它使得在没有断言的情况下运行起来太容易了,这会让你对测试产生错误的信心。
    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 2015-05-22
    • 2014-05-16
    • 1970-01-01
    • 2010-10-12
    • 2021-02-27
    • 1970-01-01
    • 2015-08-04
    相关资源
    最近更新 更多