01: package com.commsen.stopwatch;
02:
03: import org.apache.log4j.Logger;
04:
05: import com.commsen.stopwatch.engines.MemoryStopwatchEngine;
06: import com.commsen.stopwatch.reports.MemoryStopwatchReport;
07:
08: /**
09: * Unit test for {@link com.commsen.stopwatch.engines.MemoryStopwatchEngine}
10: */
11: public class MemoryStopwatchEngineTest extends
12: AbstractBaseStopwatchTest {
13:
14: /**
15: * Logger for this class
16: */
17: private static final Logger log = Logger
18: .getLogger(MemoryStopwatchEngineTest.class);
19:
20: protected final String testsGroup = "memoryEngineTests";
21:
22: /**
23: * @see com.commsen.stopwatch.AbstractBaseStopwatchTest#setUp()
24: */
25: protected void setUp() throws Exception {
26: super .setUp();
27: System.setProperty(Stopwatch.SYSTEM_PROPERTIES_PREFIX
28: + Stopwatch.PROPERTY_ENGINE,
29: MemoryStopwatchEngine.class.getName());
30: System.setProperty(Stopwatch.SYSTEM_PROPERTIES_PREFIX
31: + Stopwatch.PROPERTY_MODE, "NORMAL");
32: Stopwatch.reset();
33: }
34:
35: /**
36: *
37: *
38: */
39: public void testMemoryUsageStopwatch() {
40: getLogger().info(
41: " === special test for memory usage engine ===");
42: String testLabel = "memoryUsage";
43: for (int i = 0; i < 100; i++) {
44: generateObjects(testLabel, (int) (Math.random() * 100));
45: System.gc();
46: }
47:
48: ifThreadedModeWaitFor(100);
49: Report report = Stopwatch
50: .getSingleReport(testsGroup, testLabel);
51: assertNotNull(report);
52:
53: if (report instanceof MemoryStopwatchReport) {
54: MemoryStopwatchReport memoryStopwatchReport = (MemoryStopwatchReport) report;
55: assertTrue(memoryStopwatchReport.getAverageMemory() >= memoryStopwatchReport
56: .getMinMemory());
57: assertTrue(memoryStopwatchReport.getAverageMemory() <= memoryStopwatchReport
58: .getMaxMemory());
59:
60: // nothing else can actualy compare. It is enough it works.
61: // test result printed to STDOUT
62: } else {
63: System.out.println("Report is instance of "
64: + report.getClass().getName()
65: + " but MemoryStopwatchReport was expected! ");
66: fail();
67: }
68:
69: }
70:
71: private void generateObjects(String label, int amount) {
72: Object[] objects = new Object[amount];
73: long sw = Stopwatch.start(testsGroup, label);
74: for (int i = 0; i < amount; i++) {
75: objects[i] = new String(new char[500]);
76: }
77: try {
78: Thread.sleep((int) (Math.random() * 100));
79: } catch (InterruptedException e) {
80: e.printStackTrace();
81: }
82: Stopwatch.stop(sw);
83: }
84:
85: public Logger getLogger() {
86: return log;
87: }
88:
89: }
|