2015-12-28 69 views
0

我在代码中使用了'assert'。为什么'assert'在junit测试中没有失败

@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测试用例中使用assert吗?

更新:

我通过传递电子艺界作为VM参数启用断言。它的工作。 :)

enter image description here

回答

3

对于Java断言工作,你需要运行与电子艺界标志的应用程序/测试。尝试使用-ea标志。 Assert是JUnit特有的,并声明了该语句并且与java断言无关。

+4

btw,很多人(包括我在内)都说你不应该在测试中使用plain assert(而不是Assert类的方法)。它使得运行过程非常容易,没有断言,这会给你的测试带来错误的信心。 – yshavit