简体   繁体   English

如何强制Mockito在JUnit测试中抛出RemoteException

[英]How to force Mockito to throw RemoteException in JUnit test

This is my code which I want to force to throw a Remote Exception: 这是我想要强制抛出远程异常的代码:

transient Bicycle b=null;

public Bicycle getBicycle() {
    if(b==null) {
        try {
            b=new Bicycle(this);
        } catch (RemoteException ex) {
            Logger.getLogger(Bicycle()).log(Level.SEVERE, null, ex);
        }
    }
    return b;
}

Here is the JUnit test I am running with Mockito: 这是我与Mockito一起运行的JUnit测试:

boolean exceptionThrown=false;
Bicycle mockB = mock(Bicycle);
mockB.setBicycle(null);
stub(mockB.getBicycle()).toThrow(new RemoteException(){boolean exceptionThrown = true;});

assertTrue(exceptionThrown);

I keep receiving the following error: 我一直收到以下错误:

Checked exception is invalid for this method!

Any help will be appreciated. 任何帮助将不胜感激。

Edit: 编辑:

Instead of 代替

stub(mockB.getBicycle()).toThrow(new RemoteException(){boolean exceptionThrown = true;});

I have also tried 我也试过了

doThrow(new RemoteException(){boolean exceptionThrown = true;}).when(mockB).getBicycle();

and

Mockito.when(mockB.getBicycle()).thenThrow(new RemoteException(){boolean exceptionThrown=true;});

Still no luck. 仍然没有运气。

Edit2 - gone one step further after fully understanding the API and using it correctly: Edit2 - 在完全理解API并正确使用它之后又向前迈进了一步:

when(mockB.getBicycle()).thenThrow(new RuntimeException());

I don't know how to make the assert now. 我现在不知道怎么做断言。 I tried putting a boolean once the exception gets called but the assert cannot see the boolean. 一旦调用异常,我尝试放置一个布尔值,但断言无法看到布尔值。

Any ideas? 有任何想法吗?

The getBicycle() method will never return a RuntimeException. getBicycle()方法永远不会返回RuntimeException。 The code itself is catching the RuntimeException and, when caught, writes to the logger. 代码本身捕获RuntimeException,并在捕获时写入记录器。 The method itself will either return the Bicycle or null. 方法本身将返回Bicycle或null。

You will need to rethink how you want the getBicycle method operates. 您需要重新考虑getBicycle方法的运行方式。 It could re-throw the RuntimeException atfer logging if you want the RuntimeException to bubble through. 如果您希望RuntimeException通过,它可能会重新抛出RuntimeException atfer logging。 But, based on how that's written, the RuntmeException will never make it out to the JUnit test 但是,根据编写的方式,RuntmeException将永远不会进入JUnit测试

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

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