Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMockit Expectation API : How to throw an exception upon method/constructor invocation

Tags:

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?         } }; 
like image 748
Affan Hasan Avatar asked Mar 11 '15 16:03

Affan Hasan


People also ask

What is expectation in JMockit?

An expectation represents a set of invocations to a specific mocked method/constructor that is relevant for a given test. An expectation may cover multiple different invocations to the same method or constructor, but it doesn't have to cover all such invocations that occur during the execution of the test.

What is the difference between JMockit and Mockito?

JMockit will be the chosen option for its fixed-always-the-same structure. Mockito is more or less THE most known so that the community will be bigger. Having to call replay every time you want to use a mock is a clear no-go, so we'll put a minus one for EasyMock. Consistency/simplicity is also important for me.

What is JMockit in Java?

First of all, let's talk about what JMockit is: a Java framework for mocking objects in tests (you can use it for both JUnit and TestNG ones). It uses Java's instrumentation APIs to modify the classes' bytecode during runtime in order to dynamically alter their behavior.

What is NonStrictExpectations?

NonStrictExpectations() Registers one or more non-strict expectations recorded on available mocked types and/or mocked instances, as written inside the instance initialization body of an anonymous subclass or the called constructor of a named subclass.


1 Answers

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(); }}; 
like image 138
Rogério Avatar answered Oct 15 '22 05:10

Rogério