• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 
6 package org.mockitousage.basicapi;
7 
8 import org.junit.Test;
9 import org.mockitoutil.TestBase;
10 
11 import java.io.Serializable;
12 
13 import static junit.framework.TestCase.assertSame;
14 import static org.mockitoutil.SimpleSerializationUtil.serializeAndBack;
15 
16 @SuppressWarnings("serial")
17 public 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;
Foo()31         Foo() {
32             bar = new Bar();
33             bar.foo = this;
34         }
35     }
36 
37     @Test
shouldSerializationWork()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