Why can I “fake” the stack trace of an exception in Java?

后端 未结 6 854
梦如初夏
梦如初夏 2021-02-19 10:39

If I run the following test, it fails:

public class CrazyExceptions {
    private Exception exception;

    @Before
    public void setUp(){
        exception =          


        
6条回答
  •  误落风尘
    2021-02-19 11:14

    Because you didn't ask that that stack trace be rewritten. It was set when you created it in the setUp method, and you never did anything to alter it.

    The Exception class doesn't give you any opportunity to set the method name; it's immutable. So there's no way that I know of where you could re-set the method name, unless you wanted to resort to something heinous like reflection.

    Your @Test annotation doesn't tell me if you're using JUnit or TestNG, because I can't see the static import, but in either case you can run a test to see if a particular exception is thrown by using the "expected" member in the @Test annotation.

提交回复
热议问题