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