简体   繁体   English

JUnit测试:从内部方法调用强制异常

[英]JUnit Test : Forcing exception from internal method call

I am trying to write a test case which covers a piece of code written inside a catch block. 我正在尝试编写一个测试用例,其中包含一个写在catch块中的代码。 This is how it goes: 这是怎么回事:

I have two methods in class A . 我在A班有两种方法。

class A{

     public SomeReturnType m1()
     {
       try{
            m2();
         }catch(SomeException ex)
         {
          //handler code for SomeException (This is what I want to test). 
         }
     }

     public SomeReturnType m2() throws SomeException
     {
            //Some logic
     }
}

I am wondering How can a force this exception when m2() is called from the unit test case of method m1() ? 我想知道如何从方法m1()的单元测试用例调用m2()时强制此异常? Any solutions using Mockito or any other testing lib? 使用Mockito或任何其他测试库的任何解决方案?

As you suggested, Mockito would be a classic tool for such a usecase: 正如您所建议的,Mockito将成为这种用例的经典工具:

// Initialization - should probably be in the @Before method:
A a = Mockito.spy(new A());
Mockito.doThrow(new SomeException("yay!")).when(a).m2();

// Actual test:
SomeResult actualResult = a.m1();
assertEquals(someExpectedResult, actualResult); // or some other assertion

The above snippet creates a spy ied object (think of it as an anonymous class that extends A ) with the defined behavior that when m2() is called, a SomeException will be thrown. 上面的代码片段创建了一个spy对象(将其视为一个扩展A的匿名类),其定义的行为是,当调用m2()时,将抛出SomeException Then the code goes on to call the real m1() method, which itself calls m2() , and has to handle the exception. 然后代码继续调用真正的m1()方法,它本身调用m2() ,并且必须处理异常。

Of couse partial mock can solve your problem but there is some flaw in the design itself. 部分模拟可以解决您的问题,但设计本身存在一些缺陷。 Your API provides two methods with same signature one with richer exception management functionality. 您的API提供了两种具有相同签名的方法,具有更丰富的异常管理功能。 Pattern decorator seem to be more elegant here and no partial mock required to properly test it. 模式装饰器在这里看起来更优雅,并且不需要部分模拟来正确测试它。

If you're not interested in restructuring this class, the best way would be to use a partial mock. 如果你对重组这门课没兴趣,最好的办法就是使用局部模拟。 Stub out m2() to throw an exception when called, and then call m1(). 发出m2()以在调用时抛出异常,然后调用m1()。

Use Mockito to mock some methods but not others 使用Mockito来模拟一些方法而不是其他方法

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

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