1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.quicksearchbox.util;
18
19import static junit.framework.Assert.assertEquals;
20
21/**
22 * A task that knows how many times it has been run.
23 */
24public class MockTask implements NamedTask {
25    private final String mName;
26    private final int mId;
27    private int mRunCount = 0;
28
29    public MockTask(String name, int id) {
30        mName = name;
31        mId = id;
32    }
33
34    public String getName() {
35        return mName;
36    }
37
38    public synchronized void run() {
39        mRunCount++;
40        notifyAll();
41    }
42
43    public synchronized int getRunCount() {
44        return mRunCount;
45    }
46
47    public synchronized void waitForCompletion() throws InterruptedException {
48        while (mRunCount == 0) {
49            wait();
50        }
51    }
52
53    @Override
54    public String toString() {
55        return mName + mId;
56    }
57
58    public void assertRunCount(String message, int count) {
59        assertEquals(message + ": " + toString() + " bad run count", count, getRunCount());
60    }
61
62    public void assertRanNever(String message) {
63        assertRunCount(message, 0);
64    }
65
66    public void assertRanOnce(String message) {
67        assertRunCount(message, 1);
68    }
69
70    public static void assertRanNever(String message, MockTask... tasks) {
71        for (MockTask task : tasks) {
72            task.assertRanNever(message);
73        }
74    }
75
76    public static void assertRanOnce(String message, MockTask... tasks) {
77        for (MockTask task : tasks) {
78            task.assertRanOnce(message);
79        }
80    }
81
82}
83