How to make fun of an exception when instantiating a new class using Mockito

Inside the method, I have an exception that I want to make fun of.

I know how to mock an object to throw an exception using mock.doSomething (), but I need to throw a remote exception when the class creates a new instance itself.

transient Bicycle bike = null;

public Bicycle getBicycle() {
    if (bike == null) {
        try {
            bike = new Bicycle(this);
        } catch (RemoteException ex) {
            System.out.println("No bikes found");
        }
    }
    return bike;
}

I want to be able to make fun of everything in a try block, but I don’t understand how you mock the creation of a new class, for a specific concrete line:

bike = new Bicycle(this);

I tried many different Mockito tests, such as:

Bicycle b = mock(Bicycle.class);
Mockito.doThrow(new RemoteException()).when(b = new Bicycle());

Although I understand that this will not work, I want to do something similar.

I read the Mockito docs and found nothing useful:

http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

+5
source share
3

Mockito, PowerMock, . (. https://code.google.com/p/powermock/wiki/MockConstructor).

- :

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassUnderTest.class, Bicycle.class})
public class ConstructorMockingTest
{
    @Test
    public void getBicycle()
    {
        ClassUnderTest tested = new ClassUnderTest();
        whenNew(Bicycle.class).withArguments(tested).thenThrow(new RemoteException());

        Bicycle bicycle = tested.getBicycle();

        assertNull(bicycle);
    }
}

: https://code.google.com/p/powermock/source/browse/trunk/modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewTest.java

+3

. , PowerMock, , .

, , Bicycle. Bicycle ? , BicycleFactory, , , - BicycleFactory.createBicycle , .

- , , ; , PowerMock's.

+7

getBicycle() . ( "" ) a Bicycle, Bicycle. .

createBicycle() BicycleFactory .

0
source

All Articles