ndmhta
ndmhta

Reputation: 536

Reuse expectations block several times in JMockit

I am writing test cases for a liferay portal in which I want to mock ActionRequest, ThemeDisplay kind of objects. I have tried with writing expectations in each test method.

Now I want to generalize the approach by creating a BaseTest class which provides me all expectations needed for each method so that I don't have to write it again in the all test classes.

For one class I have tried by writing expectations in @Before method. How can I use same in different classes?

For example I want to do following in several classes:

@Before
public void setUp() {

    // All expectations which are required by each test methods
    new Expectations() {{
        themeDisplay.getPermissionChecker();
        returns(permissionChecker);
        actionRequest.getParameter("userId");
        returns("111");
        actionRequest.getParameter("userName");
        returns("User1");
    }};

}

Also is there a way to provide that whenever I call actionRequest.getParameter() it may return the specific value which I provide?

Any help will be appreciated.

Upvotes: 3

Views: 1909

Answers (1)

Rogério
Rogério

Reputation: 16390

Generally, what you want is to create named Expectations and Verifications subclasses to be reused from multiple test classes. Examples can be found in the documentation.

Note that mocked instances have to be passed in, when instantiating said subclasses.

Methods like getPermissionChecker(), however, usually don't need to be explicitly recorded, since a cascaded instance is going to be automatically returned as needed.

Mocking methods like getParameter, though, hints that perhaps it would be better to use real objects rather than mocks. Mocking isn't really meant for simple "getters", and this often indicates that you may be mocking too much.

Upvotes: 2

Related Questions