为什么 'assert' 在 junit 测试中没有失败
Why 'assert' is not failing in junit test
我在代码中使用了 'assert'。
@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 也不会失败。
如果我使用 Assert class 方法,它会按预期工作。
@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 断言起作用,您需要 运行 application/test 带有 -ea 标志。尝试使用 -ea 标志。 Assert
是特定于 JUnit 的,断言语句与 java 断言无关。
我在代码中使用了 'assert'。
@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 也不会失败。 如果我使用 Assert class 方法,它会按预期工作。
@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 断言起作用,您需要 运行 application/test 带有 -ea 标志。尝试使用 -ea 标志。 Assert
是特定于 JUnit 的,断言语句与 java 断言无关。