How to use Mock class of org.easymock package

Best Easymock code snippet using org.easymock.Mock

Run Easymock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17package org.apache.catalina.valves;
18
19import java.io.IOException;
20import java.util.Arrays;
21import java.util.Collections;
22
23import javax.servlet.ServletException;
24import javax.servlet.http.HttpSession;
25import javax.servlet.http.HttpSessionBindingListener;
26
27import org.hamcrest.CoreMatchers;
28import org.hamcrest.MatcherAssert;
29
30import org.junit.Assert;
31import org.junit.Test;
32
33import org.apache.catalina.Context;
34import org.apache.catalina.Host;
35import org.apache.catalina.Manager;
36import org.apache.catalina.Valve;
37import org.apache.catalina.connector.Request;
38import org.apache.catalina.connector.Response;
39import org.apache.catalina.core.StandardContext;
40import org.apache.catalina.session.StandardManager;
41import org.apache.catalina.session.StandardSession;
42import org.easymock.EasyMock;
43import org.easymock.IExpectationSetters;
44
45public class TestCrawlerSessionManagerValve {
46
47    private static final Manager TEST_MANAGER;
48
49    static {
50        TEST_MANAGER = new StandardManager();
51        TEST_MANAGER.setContext(new StandardContext());
52    }
53
54
55
56    @Test
57    public void testCrawlerIpsPositive() throws Exception {
58        CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
59        valve.setCrawlerIps("216\\.58\\.206\\.174");
60        valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
61        valve.setNext(EasyMock.createMock(Valve.class));
62        HttpSession session = createSessionExpectations(valve, true);
63        Request request = createRequestExpectations("216.58.206.174", session, true);
64
65        EasyMock.replay(request, session);
66
67        valve.invoke(request, EasyMock.createMock(Response.class));
68
69        EasyMock.verify(request, session);
70    }
71
72    @Test
73    public void testCrawlerIpsNegative() throws Exception {
74        CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
75        valve.setCrawlerIps("216\\.58\\.206\\.174");
76        valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
77        valve.setNext(EasyMock.createMock(Valve.class));
78        HttpSession session = createSessionExpectations(valve, false);
79        Request request = createRequestExpectations("127.0.0.1", session, false);
80
81        EasyMock.replay(request, session);
82
83        valve.invoke(request, EasyMock.createMock(Response.class));
84
85        EasyMock.verify(request, session);
86    }
87
88    @Test
89    public void testCrawlerMultipleHostsHostAware() throws Exception {
90        CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
91        valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
92        valve.setHostAware(true);
93        valve.setContextAware(true);
94        valve.setNext(EasyMock.createMock(Valve.class));
95
96        verifyCrawlingLocalhost(valve, "localhost");
97        verifyCrawlingLocalhost(valve, "example.invalid");
98    }
99
100    @Test
101    public void testCrawlerMultipleContextsContextAware() throws Exception {
102        CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
103        valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
104        valve.setHostAware(true);
105        valve.setContextAware(true);
106        valve.setNext(EasyMock.createMock(Valve.class));
107
108        verifyCrawlingContext(valve, "/examples");
109        verifyCrawlingContext(valve, null);
110    }
111
112    @Test
113    public void testCrawlersSessionIdIsRemovedAfterSessionExpiry() throws IOException, ServletException {
114        CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
115        valve.setCrawlerIps("216\\.58\\.206\\.174");
116        valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
117        valve.setNext(EasyMock.createMock(Valve.class));
118        valve.setSessionInactiveInterval(0);
119        StandardSession session = new StandardSession(TEST_MANAGER);
120        session.setId("id");
121        session.setValid(true);
122
123        Request request = createRequestExpectations("216.58.206.174", session, true);
124
125        EasyMock.replay(request);
126
127        valve.invoke(request, EasyMock.createMock(Response.class));
128
129        EasyMock.verify(request);
130
131        MatcherAssert.assertThat(valve.getClientIpSessionId().values(), CoreMatchers.hasItem("id"));
132
133        session.expire();
134
135        Assert.assertEquals(0, valve.getClientIpSessionId().values().size());
136    }
137
138
139    private void verifyCrawlingLocalhost(CrawlerSessionManagerValve valve, String hostname)
140            throws IOException, ServletException {
141        HttpSession session = createSessionExpectations(valve, true);
142        Request request = createRequestExpectations("127.0.0.1", session, true, hostname, "/examples", "tomcatBot 1.0");
143
144        EasyMock.replay(request, session);
145
146        valve.invoke(request, EasyMock.createMock(Response.class));
147
148        EasyMock.verify(request, session);
149    }
150
151
152    private void verifyCrawlingContext(CrawlerSessionManagerValve valve, String contextPath)
153            throws IOException, ServletException {
154        HttpSession session = createSessionExpectations(valve, true);
155        Request request = createRequestExpectations("127.0.0.1", session, true, "localhost", contextPath, "tomcatBot 1.0");
156
157        EasyMock.replay(request, session);
158
159        valve.invoke(request, EasyMock.createMock(Response.class));
160
161        EasyMock.verify(request, session);
162    }
163
164
165    private HttpSession createSessionExpectations(CrawlerSessionManagerValve valve, boolean isBot) {
166        HttpSession session = EasyMock.createMock(HttpSession.class);
167        if (isBot) {
168            EasyMock.expect(session.getId()).andReturn("id").times(2);
169            session.setAttribute(EasyMock.eq(valve.getClass().getName()), EasyMock.anyObject(HttpSessionBindingListener.class));
170            EasyMock.expectLastCall();
171            session.setMaxInactiveInterval(60);
172            EasyMock.expectLastCall();
173        }
174        return session;
175    }
176
177
178    private Request createRequestExpectations(String ip, HttpSession session, boolean isBot) {
179        return createRequestExpectations(ip, session, isBot, "localhost", "/examples", "something 1.0");
180    }
181
182    private Request createRequestExpectations(String ip, HttpSession session, boolean isBot, String hostname,
183            String contextPath, String userAgent) {
184        Request request = EasyMock.createMock(Request.class);
185        EasyMock.expect(request.getRemoteAddr()).andReturn(ip);
186        EasyMock.expect(request.getHost()).andReturn(simpleHostWithName(hostname));
187        EasyMock.expect(request.getContext()).andReturn(simpleContextWithName(contextPath));
188        IExpectationSetters<HttpSession> setter = EasyMock.expect(request.getSession(false))
189                .andReturn(null);
190        if (isBot) {
191            setter.andReturn(session);
192        }
193        EasyMock.expect(request.getHeaders("user-agent")).andAnswer(() -> Collections.enumeration(Arrays.asList(userAgent)));
194        return request;
195    }
196
197    private Host simpleHostWithName(String hostname) {
198        Host host = EasyMock.createMock(Host.class);
199        EasyMock.expect(host.getName()).andReturn(hostname);
200        EasyMock.replay(host);
201        return host;
202    }
203
204    private Context simpleContextWithName(String contextPath) {
205        if (contextPath == null) {
206            return null;
207        }
208        Context context = EasyMock.createMock(Context.class);
209        EasyMock.expect(context.getName()).andReturn(contextPath);
210        EasyMock.replay(context);
211        return context;
212    }
213}
214
Full Screen
copy
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package org.apache.mahout.cf.taste.impl.recommender.svd;
19
20import org.apache.mahout.cf.taste.impl.TasteTestCase;
21import org.apache.mahout.cf.taste.impl.common.FastIDSet;
22import org.apache.mahout.cf.taste.model.DataModel;
23import org.apache.mahout.cf.taste.model.PreferenceArray;
24import org.apache.mahout.cf.taste.recommender.CandidateItemsStrategy;
25import org.apache.mahout.cf.taste.recommender.RecommendedItem;
26import org.easymock.EasyMock;
27import org.junit.Test;
28
29import java.util.List;
30
31public class SVDRecommenderTest extends TasteTestCase {
32
33  @Test
34  public void estimatePreference() throws Exception {
35    DataModel dataModel = EasyMock.createMock(DataModel.class);
36    Factorizer factorizer = EasyMock.createMock(Factorizer.class);
37    Factorization factorization = EasyMock.createMock(Factorization.class);
38
39    EasyMock.expect(factorizer.factorize()).andReturn(factorization);
40    EasyMock.expect(factorization.getUserFeatures(1L)).andReturn(new double[] { 0.4, 2 });
41    EasyMock.expect(factorization.getItemFeatures(5L)).andReturn(new double[] { 1, 0.3 });
42    EasyMock.replay(dataModel, factorizer, factorization);
43
44    SVDRecommender svdRecommender = new SVDRecommender(dataModel, factorizer);
45
46    float estimate = svdRecommender.estimatePreference(1L, 5L);
47    assertEquals(1, estimate, EPSILON);
48
49    EasyMock.verify(dataModel, factorizer, factorization);
50  }
51
52  @Test
53  public void recommend() throws Exception {
54    DataModel dataModel = EasyMock.createMock(DataModel.class);
55    PreferenceArray preferencesFromUser = EasyMock.createMock(PreferenceArray.class);
56    CandidateItemsStrategy candidateItemsStrategy = EasyMock.createMock(CandidateItemsStrategy.class);
57    Factorizer factorizer = EasyMock.createMock(Factorizer.class);
58    Factorization factorization = EasyMock.createMock(Factorization.class);
59
60    FastIDSet candidateItems = new FastIDSet();
61    candidateItems.add(5L);
62    candidateItems.add(3L);
63
64    EasyMock.expect(factorizer.factorize()).andReturn(factorization);
65    EasyMock.expect(dataModel.getPreferencesFromUser(1L)).andReturn(preferencesFromUser);
66    EasyMock.expect(candidateItemsStrategy.getCandidateItems(1L, preferencesFromUser, dataModel))
67        .andReturn(candidateItems);
68    EasyMock.expect(factorization.getUserFeatures(1L)).andReturn(new double[] { 0.4, 2 });
69    EasyMock.expect(factorization.getItemFeatures(5L)).andReturn(new double[] { 1, 0.3 });
70    EasyMock.expect(factorization.getUserFeatures(1L)).andReturn(new double[] { 0.4, 2 });
71    EasyMock.expect(factorization.getItemFeatures(3L)).andReturn(new double[] { 2, 0.6 });
72
73    EasyMock.replay(dataModel, candidateItemsStrategy, factorizer, factorization);
74
75    SVDRecommender svdRecommender = new SVDRecommender(dataModel, factorizer, candidateItemsStrategy);
76
77    List<RecommendedItem> recommendedItems = svdRecommender.recommend(1L, 5);
78    assertEquals(2, recommendedItems.size());
79    assertEquals(3L, recommendedItems.get(0).getItemID());
80    assertEquals(2.0f, recommendedItems.get(0).getValue(), EPSILON);
81    assertEquals(5L, recommendedItems.get(1).getItemID());
82    assertEquals(1.0f, recommendedItems.get(1).getValue(), EPSILON);
83
84    EasyMock.verify(dataModel, candidateItemsStrategy, factorizer, factorization);
85  }
86}
87
Full Screen
copy
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package org.apache.mahout.cf.taste.impl.similarity.jdbc;
19
20import org.apache.mahout.cf.taste.impl.TasteTestCase;
21import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
22import org.easymock.EasyMock;
23import org.junit.Test;
24
25import javax.sql.DataSource;
26import java.sql.Connection;
27import java.sql.PreparedStatement;
28import java.sql.ResultSet;
29
30public class MySQLJDBCInMemoryItemSimilarityTest extends TasteTestCase {
31
32  @Test
33  public void testMemoryLoad() throws Exception {
34
35    DataSource dataSource = EasyMock.createMock(DataSource.class);
36    Connection connection = EasyMock.createMock(Connection.class);
37    PreparedStatement statement = EasyMock.createMock(PreparedStatement.class);
38    ResultSet resultSet = EasyMock.createMock(ResultSet.class);
39
40    EasyMock.expect(dataSource.getConnection()).andReturn(connection);
41    EasyMock.expect(connection.prepareStatement(MySQLJDBCInMemoryItemSimilarity.DEFAULT_GET_ALL_ITEMSIMILARITIES_SQL,
42        ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)).andReturn(statement);
43    statement.setFetchDirection(ResultSet.FETCH_FORWARD);
44    EasyMock.expect(statement.executeQuery()).andReturn(resultSet);
45
46    EasyMock.expect(resultSet.next()).andReturn(true);
47
48    EasyMock.expect(resultSet.getLong(1)).andReturn(1L);
49    EasyMock.expect(resultSet.getLong(2)).andReturn(2L);
50    EasyMock.expect(resultSet.getDouble(3)).andReturn(0.5);
51    EasyMock.expect(resultSet.next()).andReturn(true);
52
53    EasyMock.expect(resultSet.getLong(1)).andReturn(1L);
54    EasyMock.expect(resultSet.getLong(2)).andReturn(3L);
55    EasyMock.expect(resultSet.getDouble(3)).andReturn(0.4);
56    EasyMock.expect(resultSet.next()).andReturn(true);
57
58    EasyMock.expect(resultSet.getLong(1)).andReturn(3L);
59    EasyMock.expect(resultSet.getLong(2)).andReturn(4L);
60    EasyMock.expect(resultSet.getDouble(3)).andReturn(0.1);
61
62    EasyMock.expect(resultSet.next()).andReturn(false);
63
64    resultSet.close();
65    statement.close();
66    connection.close();
67
68    EasyMock.replay(dataSource, connection, statement, resultSet);
69
70    ItemSimilarity similarity = new MySQLJDBCInMemoryItemSimilarity(dataSource);
71
72    assertEquals(0.5, similarity.itemSimilarity(1L, 2L), EPSILON);
73    assertEquals(0.4, similarity.itemSimilarity(1L, 3L), EPSILON);
74    assertEquals(0.1, similarity.itemSimilarity(3L, 4L), EPSILON);
75    assertTrue(Double.isNaN(similarity.itemSimilarity(1L, 4L)));
76
77    EasyMock.verify(dataSource, connection, statement, resultSet);
78  }
79}
80
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on Mock

    No relevant questions found for this class 😞

Most used methods in Mock

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)