1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5
6package org.mockitousage.basicapi;
7
8import org.junit.Test;
9import org.mockitoutil.TestBase;
10
11import java.io.Serializable;
12
13import static junit.framework.TestCase.assertSame;
14import static org.mockitoutil.SimpleSerializationUtil.serializeAndBack;
15
16@SuppressWarnings("serial")
17public class ObjectsSerializationTest extends TestBase implements Serializable {
18
19    //Ok, this test has nothing to do with mocks but it shows fundamental feature of java serialization that
20    //plays important role in mocking:
21    //Serialization/deserialization actually replaces all instances of serialized object in the object graph (if there are any)
22    //thanks to that mechanizm, stubbing & verification can correctly match method invocations because
23    //one of the parts of invocation matching is checking if mock object is the same
24
25    class Bar implements Serializable {
26        Foo foo;
27    }
28
29    class Foo implements Serializable {
30        Bar bar;
31        Foo() {
32            bar = new Bar();
33            bar.foo = this;
34        }
35    }
36
37    @Test
38    public void shouldSerializationWork() throws Exception {
39        //given
40        Foo foo = new Foo();
41        //when
42        foo = serializeAndBack(foo);
43        //then
44        assertSame(foo, foo.bar.foo);
45    }
46}
47