01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.ioc.test;
16:
17: import org.easymock.EasyMock;
18: import org.easymock.IMocksControl;
19:
20: /**
21: * Contains core logic used by {@link TestBase}, allowing for mock objects to be used outside of a
22: * TestNG-based test suite. A <em>single</em> standard mock control is used for all mock
23: * instances. The control does not care about execution order, but will balk at any unexpected
24: * method invocations. This class is thread safe (it used a thread local to store the mock control).
25: */
26: public final class MockTester {
27: private static class ThreadLocalControl extends
28: ThreadLocal<IMocksControl> {
29: @Override
30: protected IMocksControl initialValue() {
31: return EasyMock.createControl();
32: }
33: }
34:
35: private final ThreadLocalControl _localControl = new ThreadLocalControl();
36:
37: /**
38: * Invoked after an individual unit test (i.e., a test method invocation) to discard the mock
39: * control.
40: */
41: public void cleanup() {
42: _localControl.remove();
43: }
44:
45: public IMocksControl getMocksControl() {
46: return _localControl.get();
47: }
48:
49: /**
50: * Creates a new mock object of the indicated type. The shared mock control does <strong>not</strong>
51: * check order, but does fail on any unexpected method invocations.
52: *
53: * @param <T>
54: * the type of the mock object
55: * @param mockClass
56: * the class to mock
57: * @return the mock object, ready for training
58: */
59: public <T> T newMock(Class<T> mockClass) {
60: return getMocksControl().createMock(mockClass);
61: }
62:
63: /**
64: * Switches each mock object created by {@link #newMock(Class)} into replay mode (out of the
65: * initial training mode).
66: */
67: public void replay() {
68: getMocksControl().replay();
69: }
70:
71: /**
72: * Verifies that all trained methods have been invoked on all mock objects (created by
73: * {@link #newMock(Class)}, then switches each mock object back to training mode.
74: */
75: public void verify() {
76: IMocksControl control = getMocksControl();
77:
78: control.verify();
79: control.reset();
80: }
81: }
|