View Javadoc

1   /*
2    * Copyright (c) 2003-2008 by Cosylab d. d.
3    *
4    * This file is part of Java-Common.
5    *
6    * Java-Common is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU General Public License as published by
8    * the Free Software Foundation, either version 3 of the License, or
9    * (at your option) any later version.
10   *
11   * Java-Common is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.
15   *
16   * You should have received a copy of the GNU General Public License
17   * along with Java-Common.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  package com.cosylab.util;
21  
22  import java.util.GregorianCalendar;
23  
24  /**
25   * Mock implementation of a {@link TimeProvider}, which returns pre-set time.
26   * Especially useful in unit tests. Also supports auto-advance of time (1 second
27   * by default).
28   * 
29   * @author Klemen Zagar, Cosylab
30   */
31  public class MockTimeProvider implements TimeProvider {
32  	private long millis;
33  	private long advance = 1000;
34  
35  	/**
36  	 * Constructor sets the initial mock time.
37  	 */
38  	public MockTimeProvider() {
39  		this.millis = new GregorianCalendar(2008, 1, 1, 0, 0, 0)
40  				.getTimeInMillis();
41  	}
42  
43  	/**
44  	 * Set the amount of time (in milliseconds) by which return value of
45  	 * {@linkplain #getTimeInMillis()} will advance every time it is called.
46  	 * 
47  	 * @param advance
48  	 *            Mock time provider's auto advance (in milliseconds).
49  	 */
50  	public void setAutoAdvance(long advance) {
51  		this.advance = advance;
52  	}
53  
54  	/**
55  	 * Set the current time, which will be returned the next time when
56  	 * {@link #getTimeInMillis()} is called.
57  	 * 
58  	 * @param millis
59  	 *            Current time.
60  	 */
61  	public void setTimeInMillis(long millis) {
62  		this.millis = millis;
63  	}
64  
65  	/*
66  	 * (non-Javadoc)
67  	 * 
68  	 * @see com.cosylab.util.TimeProvider#getTimeInMillis()
69  	 */
70  	public long getTimeInMillis() {
71  		// Time to return.
72  		long ret = this.millis;
73  		// Auto-advance for the next time we are called.
74  		this.millis += this.advance;
75  		return ret;
76  	}
77  }