• 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 package org.mockito.internal.stubbing;
6 
7 import org.mockito.internal.invocation.InvocationMatcher;
8 import org.mockito.invocation.DescribedInvocation;
9 import org.mockito.invocation.InvocationOnMock;
10 import org.mockito.invocation.MatchableInvocation;
11 import org.mockito.quality.Strictness;
12 import org.mockito.stubbing.Answer;
13 import org.mockito.stubbing.Stubbing;
14 
15 import java.io.Serializable;
16 import java.util.Queue;
17 import java.util.concurrent.ConcurrentLinkedQueue;
18 
19 @SuppressWarnings("unchecked")
20 public class StubbedInvocationMatcher extends InvocationMatcher implements Serializable, Stubbing {
21 
22     private static final long serialVersionUID = 4919105134123672727L;
23     private final Queue<Answer> answers = new ConcurrentLinkedQueue<Answer>();
24     private final Strictness strictness;
25     private DescribedInvocation usedAt;
26 
StubbedInvocationMatcher(Answer answer, MatchableInvocation invocation, Strictness strictness)27     public StubbedInvocationMatcher(Answer answer, MatchableInvocation invocation, Strictness strictness) {
28         super(invocation.getInvocation(), invocation.getMatchers());
29         this.strictness = strictness;
30         this.answers.add(answer);
31     }
32 
answer(InvocationOnMock invocation)33     public Object answer(InvocationOnMock invocation) throws Throwable {
34         //see ThreadsShareGenerouslyStubbedMockTest
35         Answer a;
36         synchronized(answers) {
37             a = answers.size() == 1 ? answers.peek() : answers.poll();
38         }
39         return a.answer(invocation);
40     }
41 
addAnswer(Answer answer)42     public void addAnswer(Answer answer) {
43         answers.add(answer);
44     }
45 
markStubUsed(DescribedInvocation usedAt)46     public void markStubUsed(DescribedInvocation usedAt) {
47         this.usedAt = usedAt;
48     }
49 
wasUsed()50     public boolean wasUsed() {
51         return usedAt != null;
52     }
53 
54     @Override
toString()55     public String toString() {
56         return super.toString() + " stubbed with: " + answers;
57     }
58 
59     @Override
getStrictness()60     public Strictness getStrictness() {
61         return strictness;
62     }
63 }
64