简体   繁体   English

Java 单元测试 - 未抛出异常

[英]Java unit test - exception not being thrown

Trying to write a test that will call my method, when that method makes a call to another method we will throw a custom exception i have made.尝试编写将调用我的方法的测试,当该方法调用另一个方法时,我们将抛出我所做的自定义异常。 Here i have simplified it all在这里,我已经简化了一切

2 functions 2个功能

public MyJsonResponse hello() {
        MyJsonResponse response = new MyJsonResponse();
        response.setErrorMessage("1");
        response.setStatus("some status");
        response.setData("1");
        response.setHttpResponse(200);
        try{
            hi();
            return response;
        }catch (MyServiceException e) {
            response.setErrorMessage(e.getMessage());
            response.setStatus("error creating");
            response.setData("2");
            response.setHttpResponse(e.getResponseStatus());
            return response;
        }

    }

    public String hi() throws  MyServiceException{
        LOG.error("Exception");
        return "yea";
    }

The test I have written is this我写的测试是这样的

    @Test
    public void myTest() throws Exception {

        given(service.hi()).willAnswer( invocation -> { throw new MyServiceException("abc msg",511); });
        MyJsonResponse actual = service.hello();

        Assert.assertNotNull(actual);
        assertEquals(511, actual.getHttpResponse());
    }

But unfortunately the result is as follows但不幸的是结果如下

java.lang.AssertionError: 
Expected :511
Actual   :200

regarding what you explain and what your code look like, I am not sure if I have well understood.关于你解释的内容和你的代码是什么样的,我不确定我是否理解得很好。 Thus, if you want that, your hi(): function throws an exception.因此,如果您愿意,您的 hi(): function 会引发异常。 You have to make it first throws an exception.你必须让它首先抛出一个异常。 Take a look at code below!看看下面的代码!

 public String hi() throws  MyServiceException{
        /*LOG.error("Exception");//No don't just log, throw a real exception as below*/
       throw new MyServiceException("text here, if your constructor support it or nothing otherwise")
     /*return "yea";//Nothing to return? we have just break the code by throwing the exception above*/
    }

After that, please be very sure that your 'MyServiceException.getHttpResponse()' will really return 511之后,请确保您的 'MyServiceException.getHttpResponse()' 真的会返回 511

Please, be sure that you are using a spy as you want to use the actual code for some methods of your mocked service and just stubbing specific methods of it.请确保您使用的是spy ,因为您想将实际代码用于您的模拟服务的某些方法,并且只是对它的特定方法进行存根。 Please, see for instance this related SO question about the subject.请参阅这个关于该主题的相关 SO 问题

Also, consider modifying your test definition to use willThrow instead of willAnswer : as pointed out by @eis, you can still use the later, but the former is more straightforward.另外,考虑修改您的测试定义以使用willThrow而不是willAnswer :正如@eis 所指出的,您仍然可以使用后者,但前者更直接。

Your code will look similar to this:您的代码将与此类似:

@Test
public void myTest() throws Exception {
  MyService service = spy(MyService.class);

  willThrow(new MyServiceException("abc msg",511))
    .given(service)
    .hi()
  ;

  // As pointed out by @eis, you can still use willAnswer
  // willAnswer(
  //   invocation -> { throw new MyServiceException("abc msg",511);}
  // )
  //   .given(service)
  //   .hi()
  // ;

  
  MyJsonResponse actual = service.hello();

  Assert.assertNotNull(actual);
  assertEquals(511, actual.getHttpResponse());
}

For this test to make sense, your hi() call should be done calling another service that you stub/mock in your test class.为了使这个测试有意义,你的 hi() 调用应该调用另一个你在测试 class 中存根/模拟的服务。 You're not doing that, so this approach won't work.你不这样做,所以这种方法行不通。

You wrote "the real method that hi represents does a lot", so it's about time you extract that to another service.你写了“hi 代表的真实方法做了很多”,所以现在是时候将它提取到另一个服务中了。

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

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