22

While using JMockit I want to throw an exception upon a constructor invocation like this:

new Expectations(){
        {
           new FirefoxDriver();//Want to throw IllegalStateException here but how?
        }
};
Affan Hasan
  • 334
  • 1
  • 4
  • 16

2 Answers2

28

To specify the result for a recorded expectation, assign it (either values to return or exceptions to throw) to the result field:

new Expectations() {{
    someMockedMethodOrConstructorInvocation(...); result = new IllegalStateException();
}};
Rogério
  • 16,171
  • 2
  • 50
  • 63
  • I have tried the above; but instead of mocking, it is calling the actual constructor & creating objects instead :( – Affan Hasan Mar 16 '15 at 12:05
  • 2
    You can only record an expectation on a method or constructor which has been *mocked*; usually, that means you declare a mock field or mock parameter using one of the mocking annotations, such as "`@Mocked`". Otherwise, the actual method or constructor is indeed going to be executed. – Rogério Mar 16 '15 at 17:18
  • @Rogério: adding the mocked field to your example would've been nice. :-) I _think_ it should just be `new Expectations(FirefoxDriver.class) {{...}};` for Affan's case, but am not confident enough with JMockit yet... Maybe add `@Test(expected = IllegalStateException)` to the method, and then call `new FirefoxDriver();` after the expectations block? – Amos M. Carpenter Sep 16 '16 at 06:37
0

we should add the class to be mocked as parameters in the method of the test case.and using result, we can mock the outcome of the method.

@Test
    public void testCase(@Mocked final ClassToMock classToMockObject){  

         new NonStrictExpectations() {
                {       
        classToMockObject.methodToMock();result=NullPointerException(); 
            }};

        classToMockObject.methodToMock(); //calling the method to throw exception
    }
Keshav
  • 1,123
  • 1
  • 18
  • 36