1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.stubbing;
6
7import java.io.Serializable;
8import java.util.Queue;
9import java.util.concurrent.ConcurrentLinkedQueue;
10
11import org.mockito.internal.invocation.InvocationMatcher;
12import org.mockito.invocation.DescribedInvocation;
13import org.mockito.invocation.InvocationOnMock;
14import org.mockito.stubbing.Answer;
15
16@SuppressWarnings("unchecked")
17public class StubbedInvocationMatcher extends InvocationMatcher implements Answer, Serializable {
18
19    private static final long serialVersionUID = 4919105134123672727L;
20    private final Queue<Answer> answers = new ConcurrentLinkedQueue<Answer>();
21    private DescribedInvocation usedAt;
22
23    public StubbedInvocationMatcher(InvocationMatcher invocation, Answer answer) {
24        super(invocation.getInvocation(), invocation.getMatchers());
25        this.answers.add(answer);
26    }
27
28    public Object answer(InvocationOnMock invocation) throws Throwable {
29        //see ThreadsShareGenerouslyStubbedMockTest
30        Answer a;
31        synchronized(answers) {
32            a = answers.size() == 1 ? answers.peek() : answers.poll();
33        }
34        return a.answer(invocation);
35    }
36
37    public void addAnswer(Answer answer) {
38        answers.add(answer);
39    }
40
41    public void markStubUsed(DescribedInvocation usedAt) {
42        this.usedAt = usedAt;
43    }
44
45    public boolean wasUsed() {
46        return usedAt != null;
47    }
48
49    @Override
50    public String toString() {
51        return super.toString() + " stubbed with: " + answers;
52    }
53}