简体   繁体   English

Java AssertEquals赶上

[英]Java AssertEquals in catch

    @Test
  void testSomething() {
    try {
      //something that would throw an exception.
  } catch (Exception e) {
    assertEquals(true, false);
  }

If I have something like this in my j unit test, would the test still fail? 如果我的j单元测试中有类似的内容,测试是否仍会失败?

EDIT: Sorry should've stated earlier, I'm not trying to achieve anything here this is part of my midterm and someone told me any assertEquals in catch will always pass and I was confused about that. 编辑:对不起,我应该早些时候说,我不是在这里取得任何成就,这是我期中考试的一部分,有人告诉我,任何assertEquals总是会过去,对此我感到困惑。

It would still fail, because you're trying to assert a condition that will never be true: 它仍然会失败,因为您正在尝试声明一个永远不会成立的条件:

assertEquals(true, false);

That will, by itself, throw an AssertionError , which is not being caught, so the overall unit test will fail. 这本身将引发一个AssertionError ,而该错误不会被捕获,因此整个单元测试将失败。

The preferred way of asserting exception is by using expected like this: for example, you expect the test should throw ArithmeticException 断言异常的首选方法是使用期望值,例如:例如,您期望测试应该抛出ArithmeticException

@Test(expected = ArithmeticException.class)
public void div_shouldThrowArithmeticExceptionWhenDivisorIsZero() {
    int a = 10, b = 0;
    div(a,b);
}

if you specify @Test(expected = SomeExpectedException.class) , then the test will pass when the test code block generate the expected Exception. 如果指定@Test(expected = SomeExpectedException.class) ,则当测试代码块生成预期的Exception时,测试将通过。

Whenever exception throws from try block your assertequals in catch block will execute but I'm not sure about your intention of doing that. 每当try块引发异常时,catch块中的assertequals就会执行,但是我不确定您打算这样做。 If you want to assert about your exception you can do that by assert Throws. 如果要断言异常,可以通过断言Throws来实现。

I hope this answer helps 我希望这个答案有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM