+/*
+ * Copyright 2005-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.persistence;
+
+import static org.mockito.Mockito.*;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static junit.framework.TestCase.*;
+
+public class AbstractDetachableTest {
+
+ public static class X {
+
+ }
+
+ public static interface DetachableMethods {
+ Integer getReference(X aObject);
+
+ X load(Integer aReference);
+ }
+
+ public class MyDetachable extends AbstractDetachable<X, Integer> {
+
+ public MyDetachable(X aObj) {
+ super(aObj);
+ }
+
+ @Override
+ protected Integer getReference(X aObject) {
+ return methods.getReference(aObject);
+ }
+
+ @Override
+ protected X load(Integer aReference) {
+ return methods.load(aReference);
+ }
+
+ }
+
+ private DetachableMethods methods;
+ private AbstractDetachable<X, Integer> detachable;
+ private X x;
+
+ @Before
+ public void setUp() {
+ methods = mock(DetachableMethods.class);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testNullPassedIn() {
+ detachable = new MyDetachable(null);
+ }
+
+ @Test
+ public void testDetach() {
+ x = new X();
+ Integer ref = 100;
+ when(methods.getReference(any(X.class))).thenReturn(ref);
+ detachable = new MyDetachable(x);
+ verifyNoMoreInteractions(methods);
+ detachable.detach();
+ verify(methods).getReference(same(x));
+ assertNull(detachable.getObject());
+ assertEquals(ref, detachable.getReference());
+ }
+
+ @Test
+ public void testDetachTwice() {
+ reset(methods);
+ testDetach();
+ detachable.detach();
+ detachable.detach();
+ verifyNoMoreInteractions(methods);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testDetachWithNullReference() {
+ x = new X();
+ Integer ref = 100;
+ when(methods.getReference(any(X.class))).thenReturn(null);
+ detachable = new MyDetachable(x);
+ verifyNoMoreInteractions(methods);
+ detachable.detach();
+ }
+
+ @Test
+ public void testReattach() {
+ testDetach();
+ reset(methods);
+
+ X x2 = new X(); // the new X loaded from persistent storage.
+ when(methods.load(detachable.getReference())).thenReturn(x2);
+
+ X x3 = detachable.get();
+ verify(methods).load(100);
+ assertSame(x2, x3);
+
+ assertSame(x2, detachable.getObject());
+ }
+
+ @Test
+ public void testGetInvokedTwiceNoLoads() {
+ testReattach();
+ reset(methods);
+ detachable.get();
+ detachable.get();
+ verifyNoMoreInteractions(methods);
+ }
+
+
+}