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.stubbing; 7 8 import org.junit.Test; 9 import org.mockito.internal.stubbing.answers.ClonesArguments; 10 import org.mockitoutil.TestBase; 11 12 import java.util.List; 13 14 import static org.junit.Assert.assertNotNull; 15 import static org.mockito.Mockito.*; 16 17 public class CloningParameterTest extends TestBase { 18 19 @Test shouldVerifyEvenIfArgumentsWereMutated()20 public void shouldVerifyEvenIfArgumentsWereMutated() throws Exception { 21 22 // given 23 EmailSender emailSender = mock(EmailSender.class, new ClonesArguments()); 24 25 // when 26 businessLogic(emailSender); 27 28 // then 29 verify(emailSender).sendEmail(1, new Person("Wes")); 30 } 31 businessLogic(EmailSender emailSender)32 private void businessLogic(EmailSender emailSender) { 33 Person person = new Person("Wes"); 34 emailSender.sendEmail(1, person); 35 person.emailSent(); 36 } 37 38 @Test shouldReturnDefaultValueWithCloningAnswer()39 public void shouldReturnDefaultValueWithCloningAnswer() throws Exception { 40 41 // given 42 EmailSender emailSender = mock(EmailSender.class, new ClonesArguments()); 43 when(emailSender.getAllEmails(new Person("Wes"))).thenAnswer(new ClonesArguments()); 44 45 // when 46 List<?> emails = emailSender.getAllEmails(new Person("Wes")); 47 48 // then 49 assertNotNull(emails); 50 } 51 52 public class Person { 53 54 private final String name; 55 private boolean emailSent; 56 Person(String name)57 public Person(String name) { 58 this.name = name; 59 } 60 emailSent()61 public void emailSent() { 62 emailSent = true; 63 } 64 65 @Override hashCode()66 public int hashCode() { 67 final int prime = 31; 68 int result = 1; 69 result = prime * result + getOuterType().hashCode(); 70 result = prime * result + (emailSent ? 1231 : 1237); 71 result = prime * result + ((name == null) ? 0 : name.hashCode()); 72 return result; 73 } 74 75 @Override equals(Object obj)76 public boolean equals(Object obj) { 77 if (this == obj) 78 return true; 79 if (obj == null) 80 return false; 81 if (getClass() != obj.getClass()) 82 return false; 83 Person other = (Person) obj; 84 if (!getOuterType().equals(other.getOuterType())) 85 return false; 86 if (emailSent != other.emailSent) 87 return false; 88 if (name == null) { 89 if (other.name != null) 90 return false; 91 } else if (!name.equals(other.name)) 92 return false; 93 return true; 94 } 95 getOuterType()96 private CloningParameterTest getOuterType() { 97 return CloningParameterTest.this; 98 } 99 100 } 101 102 public interface EmailSender { 103 sendEmail(int i, Person person)104 void sendEmail(int i, Person person); 105 getAllEmails(Person person)106 List<?> getAllEmails(Person person); 107 108 } 109 } 110