Best junit code snippet using org.junit.rules.Stopwatch
Source:JunitRuleTest.java
1package com.github.testframework.junit4;2import com.google.common.base.Stopwatch;3import lombok.extern.slf4j.Slf4j;4import org.apache.commons.io.FileUtils;5import org.junit.Rule;6import org.junit.Test;7import org.junit.rules.ExpectedException;8import org.junit.rules.MethodRule;9import org.junit.rules.RuleChain;10import org.junit.rules.TemporaryFolder;11import org.junit.rules.TestName;12import org.junit.rules.TestRule;13import org.junit.rules.Timeout;14import org.junit.runner.Description;15import org.junit.runner.RunWith;16import org.junit.runners.model.FrameworkMethod;17import org.junit.runners.model.Statement;18import org.springframework.boot.test.context.SpringBootTest;19import org.springframework.test.context.junit4.SpringRunner;20import java.io.File;21import java.util.concurrent.TimeUnit;22/**23 * JunitRuleTest24 *25 * @author dongdaiming(è£ä»£æ)26 * @date 2019-07-2227 * @see <a href="https://blog.csdn.net/kingmax54212008/article/details/89003076">Junit Ruleç使ç¨</a>28 */29@Slf4j30@RunWith(SpringRunner.class)31@SpringBootTest32public class JunitRuleTest {33 // TemporaryFolderå¯ç¨äºå¨æµè¯æ¶çææ件并å¨æµè¯å®åèªå¨å é¤34 @Rule35 public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("/temp/junit"));36 // TestNameå¯ä»¥è·åå°å½åæµè¯æ¹æ³çå称37 @Rule38 public TestName testName = new TestName();39 // Timeoutå¯ä»¥è®¾ç½®å
¨å±çè¶
æ¶æ¶é´40 @Rule41 public Timeout timeout = Timeout.seconds(15);42 // èªå®ä¹æ¹æ³è§å-æå°æµè¯æ¹æ³åä¸èæ¶43 @Rule44 public MethodLoggingRule methodLogger = new MethodLoggingRule();45 // ExpectedExceptionå¯ä»¥å¹é
å¼å¸¸ç±»ååå¼å¸¸message46 @Rule47 public ExpectedException expectedException = ExpectedException.none();48 @Rule49 public RuleChain ruleChain = RuleChain.outerRule(new LoggingRule(3)).around(new LoggingRule(2)).around(new LoggingRule(1));50 @Test51 public void testTemporaryFolder() throws Exception {52 File file = temporaryFolder.newFile();53 log.info("file: {}", file.getAbsolutePath());54 FileUtils.writeStringToFile(file, "abc", "utf-8", true);55 log.info("read data: {}", FileUtils.readFileToString(file, "utf-8"));56 TimeUnit.SECONDS.sleep(10);57 }58 @Test59 public void testTimeout() throws InterruptedException {60 TimeUnit.SECONDS.sleep(20);61 }62 @Test63 public void testNotTimeout() throws InterruptedException {64 TimeUnit.SECONDS.sleep(1);65 }66 @Test67 public void testMethodLogRule() throws InterruptedException {68 TimeUnit.MILLISECONDS.sleep(1234);69 }70 @Test71 public void testExpectException1() {72 expectedException.expect(NumberFormatException.class);73 expectedException.expectMessage("For input string: \"a\"");74 Integer.parseInt("a");75 }76 @Test(expected = ArithmeticException.class)77 public void testExpectException2() {78 int n = 1 / 0;79 }80 @Test81 public void testRuleChain() {82 }83 @Slf4j84 private static class MethodLoggingRule implements MethodRule {85 @Override86 public Statement apply(Statement base, FrameworkMethod method, Object target) {87 String flag = target.getClass().getSimpleName() + "." + method.getName();88 return new Statement() {89 @Override90 public void evaluate() throws Throwable {91 Stopwatch watch = Stopwatch.createStarted();92 base.evaluate();93 log.info("finished {}, duration: {} ms.", flag, watch.elapsed(TimeUnit.MILLISECONDS));94 }95 };96 }97 }98 @Slf4j99 private static class LoggingRule implements TestRule {100 private int priority;101 public LoggingRule(int priority) {102 this.priority = priority;103 }104 @Override105 public Statement apply(Statement base, Description description) {...
Source:Stopwatch.java
2import java.util.concurrent.TimeUnit;3import org.junit.AssumptionViolatedException;4import org.junit.runner.Description;5import org.junit.runners.model.Statement;6public abstract class Stopwatch implements TestRule {7 private final Clock clock;8 private volatile long endNanos;9 private volatile long startNanos;10 public Stopwatch() {11 this(new Clock());12 }13 Stopwatch(Clock clock2) {14 this.clock = clock2;15 }16 public long runtime(TimeUnit unit) {17 return unit.convert(getNanos(), TimeUnit.NANOSECONDS);18 }19 /* access modifiers changed from: protected */20 public void succeeded(long nanos, Description description) {21 }22 /* access modifiers changed from: protected */23 public void failed(long nanos, Throwable e, Description description) {24 }25 /* access modifiers changed from: protected */26 public void skipped(long nanos, AssumptionViolatedException e, Description description) {27 }28 /* access modifiers changed from: protected */29 public void finished(long nanos, Description description) {30 }31 /* access modifiers changed from: private */32 /* access modifiers changed from: public */33 private long getNanos() {34 if (this.startNanos != 0) {35 long currentEndNanos = this.endNanos;36 if (currentEndNanos == 0) {37 currentEndNanos = this.clock.nanoTime();38 }39 return currentEndNanos - this.startNanos;40 }41 throw new IllegalStateException("Test has not started");42 }43 /* access modifiers changed from: private */44 /* access modifiers changed from: public */45 private void starting() {46 this.startNanos = this.clock.nanoTime();47 this.endNanos = 0;48 }49 /* access modifiers changed from: private */50 /* access modifiers changed from: public */51 private void stopping() {52 this.endNanos = this.clock.nanoTime();53 }54 @Override // org.junit.rules.TestRule55 public final Statement apply(Statement base, Description description) {56 return new InternalWatcher().apply(base, description);57 }58 private class InternalWatcher extends TestWatcher {59 private InternalWatcher() {60 }61 /* access modifiers changed from: protected */62 @Override // org.junit.rules.TestWatcher63 public void starting(Description description) {64 Stopwatch.this.starting();65 }66 /* access modifiers changed from: protected */67 @Override // org.junit.rules.TestWatcher68 public void finished(Description description) {69 Stopwatch stopwatch = Stopwatch.this;70 stopwatch.finished(stopwatch.getNanos(), description);71 }72 /* access modifiers changed from: protected */73 @Override // org.junit.rules.TestWatcher74 public void succeeded(Description description) {75 Stopwatch.this.stopping();76 Stopwatch stopwatch = Stopwatch.this;77 stopwatch.succeeded(stopwatch.getNanos(), description);78 }79 /* access modifiers changed from: protected */80 @Override // org.junit.rules.TestWatcher81 public void failed(Throwable e, Description description) {82 Stopwatch.this.stopping();83 Stopwatch stopwatch = Stopwatch.this;84 stopwatch.failed(stopwatch.getNanos(), e, description);85 }86 /* access modifiers changed from: protected */87 @Override // org.junit.rules.TestWatcher88 public void skipped(AssumptionViolatedException e, Description description) {89 Stopwatch.this.stopping();90 Stopwatch stopwatch = Stopwatch.this;91 stopwatch.skipped(stopwatch.getNanos(), e, description);92 }93 }94 /* access modifiers changed from: package-private */95 public static class Clock {96 Clock() {97 }98 public long nanoTime() {99 return System.nanoTime();100 }101 }102}...
Source:CommonUnitTest.java
...16import java.util.concurrent.TimeUnit;17import org.junit.rules.TestRule;18import org.junit.rules.TestWatcher;19import org.junit.runner.Description;20import com.google.common.base.Stopwatch;21/**22 * Class providing uniform unit test functionality.23 * 24 * @author James G. Willmore25 *26 */27public class CommonUnitTest extends TestWatcher implements TestRule {28 /** The logger. */29 private static Logger logger = LoggerFactory.getLogger(CommonUnitTest.class);30 /** The test stopwatch. */31 private final Stopwatch testStopwatch = Stopwatch.createUnstarted();32 /**33 * @see org.junit.rules.TestWatcher#starting(org.junit.runner.Description)34 */35 protected void starting(Description description) {36 logger.info("===== BEGIN {} [{}] =====", description.getMethodName(),37 description.getClassName());38 testStopwatch.start();39 }40 /**41 * @see org.junit.rules.TestWatcher#finished(org.junit.runner.Description)42 */43 protected void finished(Description description) {44 testStopwatch.stop();45 long elapsed = testStopwatch.elapsed(TimeUnit.MILLISECONDS);46 logger.info("Elapsed time: {} ms", elapsed);47 logger.info("===== END {} [{}] =====", description.getMethodName(),48 description.getClassName());49 }50}...
Source:TimingRules.java
1package ru.javaprojects.restaurant_vote_system;2import org.junit.rules.ExternalResource;3import org.junit.rules.Stopwatch;4import org.junit.runner.Description;5import org.slf4j.Logger;6import org.slf4j.LoggerFactory;7import java.util.concurrent.TimeUnit;8public class TimingRules {9 private static final Logger log = LoggerFactory.getLogger("result");10 private static StringBuilder results = new StringBuilder();11 // http://stackoverflow.com/questions/14892125/what-is-the-best-practice-to-determine-the-execution-time-of-the-bussiness-relev12 public static final Stopwatch STOPWATCH = new Stopwatch() {13 @Override14 protected void finished(long nanos, Description description) {15 String result = String.format("%-95s %7d", description.getDisplayName(), TimeUnit.NANOSECONDS.toMillis(nanos));16 results.append(result).append('\n');17 log.info(result + " ms\n");18 }19 };20 public static final ExternalResource SUMMARY = new ExternalResource() {21 @Override22 protected void before() throws Throwable {23 results.setLength(0);24 }25 @Override26 protected void after() {...
Source:AbstractServiceTest.java
2import org.junit.ClassRule;3import org.junit.Rule;4import org.junit.rules.ExpectedException;5import org.junit.rules.ExternalResource;6import org.junit.rules.Stopwatch;7import org.junit.runner.RunWith;8import org.slf4j.bridge.SLF4JBridgeHandler;9import org.springframework.test.context.ContextConfiguration;10import org.springframework.test.context.jdbc.Sql;11import org.springframework.test.context.jdbc.SqlConfig;12import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;13import ru.kolesnikov.votingsystem.TimingRules;14@ContextConfiguration({15 "classpath:spring/spring-app.xml",16 "classpath:spring/spring-db.xml"17})18@RunWith(SpringJUnit4ClassRunner.class)19@Sql(scripts = "classpath:db/populateDB.sql", config = @SqlConfig(encoding = "UTF-8"))20public abstract class AbstractServiceTest {21 @ClassRule22 public static ExternalResource summary = TimingRules.SUMMARY;23 @Rule24 public Stopwatch stopwatch = TimingRules.STOPWATCH;25 @Rule26 public ExpectedException thrown = ExpectedException.none();27 static {28 // needed only for java.util.logging (postgres driver)29 SLF4JBridgeHandler.install();30 }31}
Source:AbstractBaseRepositoryTest.java
2import org.assertj.core.api.Assertions;3import org.junit.ClassRule;4import org.junit.Rule;5import org.junit.rules.ExternalResource;6import org.junit.rules.Stopwatch;7import org.junit.runner.RunWith;8import org.springframework.test.context.ContextConfiguration;9import org.springframework.test.context.jdbc.Sql;10import org.springframework.test.context.jdbc.SqlConfig;11import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;12import ru.javaprojects.restaurant_vote_system.TimingRules;13@ContextConfiguration({14 "classpath:spring/spring-database.xml"15})16@RunWith(SpringJUnit4ClassRunner.class)17@Sql(scripts = {"/db/init_db_hsql.sql", "/db/populate_db_with_test_data_hsql.sql"}, config = @SqlConfig(encoding = "UTF-8"))18public abstract class AbstractBaseRepositoryTest extends Assertions {19 @ClassRule20 public static ExternalResource SUMMARY = TimingRules.SUMMARY;21 @Rule22 public Stopwatch stopwatch = TimingRules.STOPWATCH;23}...
Source:BaseJobTest.java
1package ru.sber.ekvit.job;2import org.junit.ClassRule;3import org.junit.Rule;4import org.junit.rules.ExternalResource;5import org.junit.rules.Stopwatch;6import org.junit.runner.RunWith;7import org.springframework.boot.test.context.SpringBootTest;8import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;9import static org.junit.Assert.*;10@RunWith(SpringJUnit4ClassRunner.class)11@SpringBootTest12public abstract class BaseJobTest {13 @ClassRule14 public static ExternalResource SUMMARY = TimingRules.SUMMARY;15 @Rule16 public Stopwatch stopwatch = TimingRules.STOPWATCH;17}...
Source:Stopwatch$InternalWatcher.java
1class org.junit.rules.Stopwatch$InternalWatcher extends org.junit.rules.TestWatcher {2 final org.junit.rules.Stopwatch this$0;3 protected void starting(org.junit.runner.Description);4 protected void finished(org.junit.runner.Description);5 protected void succeeded(org.junit.runner.Description);6 protected void failed(java.lang.Throwable, org.junit.runner.Description);7 protected void skipped(org.junit.AssumptionViolatedException, org.junit.runner.Description);8 org.junit.rules.Stopwatch$InternalWatcher(org.junit.rules.Stopwatch, org.junit.rules.Stopwatch$1);9}...
Stopwatch
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.Stopwatch;4import org.junit.runner.Description;5import java.util.concurrent.TimeUnit;6public class StopwatchTest {7 public Stopwatch stopwatch = new Stopwatch() {8 protected void finished(long nanos, Description description) {9 System.out.println("Test " + description.getMethodName() + " took " + nanos + " nanoseconds");10 }11 };12 public void test1() throws InterruptedException {13 TimeUnit.SECONDS.sleep(1);14 }15 public void test2() throws InterruptedException {16 TimeUnit.SECONDS.sleep(2);17 }18}19import org.junit.jupiter.api.Test;20import org.junit.platform.commons.util.StopWatch;21import java.util.concurrent.TimeUnit;22public class StopwatchTest {23 public void test1() throws InterruptedException {24 StopWatch stopWatch = StopWatch.start();25 TimeUnit.SECONDS.sleep(1);26 stopWatch.stop();27 System.out.println("Test 1 took " + stopWatch.getTotalTimeMillis() + " milliseconds");28 }29 public void test2() throws InterruptedException {30 StopWatch stopWatch = StopWatch.start();31 TimeUnit.SECONDS.sleep(2);32 stopWatch.stop();33 System.out.println("Test 2 took " + stopWatch.getTotalTimeMillis() + " milliseconds");34 }35}36How to use JUnit 5 @RepeatedTest and @RepeatedTest(value = 5, name = "{displayName} {currentRepetition}/{totalRepetitions}") annotations ?
Stopwatch
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.Stopwatch;4import org.junit.runner.Description;5import java.util.concurrent.TimeUnit;6public class StopwatchTest {7 public Stopwatch stopwatch = new Stopwatch() {8 protected void finished(long nanos, Description description) {9 System.out.println(description.getDisplayName() + " took " + nanos + " nanoseconds.");10 }11 };12 public void test1() throws Exception {13 Thread.sleep(1000);14 }15 public void test2() throws Exception {16 Thread.sleep(2000);17 }18}19package com.journaldev.junit.rules;20import org.junit.Rule;21import org.junit.Test;22import org.junit.rules.Stopwatch;23import org.junit.runner.Description;24import java.util.concurrent.TimeUnit;25public class StopwatchExample {26 public Stopwatch stopwatch = new Stopwatch() {27 protected void finished(long nanos, Description description) {28 System.out.println(description.getDisplayName() + " took " + nanos / 1000000 + " milliseconds.");29 }30 };31 public void test1() throws Exception {32 Thread.sleep(1000);33 }34 public void test2() throws Exception {35 Thread.sleep(2000);36 }37}38package com.journaldev.junit.rules;39import org.junit.Rule;40import org.junit.Test;41import org.junit.rules.Stopwatch;42import org.junit.runner.Description;43import java.util.concurrent.TimeUnit;44public class StopwatchTimeoutExample {45 public Stopwatch stopwatch = new Stopwatch() {46 protected void finished(long nanos, Description description) {
Stopwatch
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.Stopwatch;4public class StopwatchTest {5 public Stopwatch stopwatch = new Stopwatch() {6 protected void succeeded(long nanos, org.junit.runner.Description description) {7 System.out.println("Test " + description.getDisplayName() + " succeeded");8 }9 protected void failed(long nanos, Throwable e, org.junit.runner.Description description) {10 System.out.println("Test " + description.getDisplayName() + " failed");11 }12 protected void finished(long nanos, org.junit.runner.Description description) {13 System.out.println("Test " + description.getDisplayName() + " finished");14 }15 };16 public void testOne() throws InterruptedException {17 Thread.sleep(1000);18 }19 public void testTwo() throws InterruptedException {20 Thread.sleep(2000);21 }22}23Test testOne() succeeded24Test testOne() finished25Test testTwo() succeeded26Test testTwo() finished27public Stopwatch stopwatch = new Stopwatch();28protected void succeeded(long nanos, Description description)29protected void failed(long nanos, Throwable e, Description description)30protected void finished(long nanos, Description description)31import org.junit.Rule;32import org.junit.Test;33import org.junit.rules.Stopwatch;34import org.junit.runner.Description;35public class StopwatchTest {36 public Stopwatch stopwatch = new Stopwatch() {37 protected void succeeded(long nanos, Description description) {38 System.out.println("Test " + description.getDisplayName() + " succeeded");39 }40 protected void failed(long nanos, Throwable e, Description description) {41 System.out.println("Test " + description.getDisplayName() + " failed");42 }43 protected void finished(long nanos, Description description) {44 System.out.println("Test " + description.getDisplayName() + " finished");45 }46 };47 public void testOne() throws InterruptedException {
Stopwatch
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.Stopwatch;4import org.junit.runner.Description;5public class TestStopwatch {6 public Stopwatch stopwatch = new Stopwatch() {7 protected void finished(long nanos, Description description) {8 System.out.println("Finished in " + nanos + " nanos");9 }10 };11 public void test() throws Exception {12 Thread.sleep(1000);13 }14}15import org.junit.Rule;16import org.junit.Test;17import org.junit.rules.Stopwatch;18import org.junit.runner.Description;19public class TestStopwatch {20 public Stopwatch stopwatch = new Stopwatch() {21 protected void finished(long nanos, Description description) {22 System.out.println("Finished in " + nanos + " nanos");23 }24 };25 public void test() throws Exception {26 Thread.sleep(1000);27 }28}29Stopwatch class of org.junit.rules package is used to measure the time taken by a test method to run. It can be used to find out the performance of a test method. It is used by creating an anonymous class of Stopwatch and overriding the finished() method. The finished() method is
Stopwatch
Using AI Code Generation
1package com.javatpoint; 2import org.junit.rules.*; 3import org.junit.runner.Description; 4import org.junit.runners.model.Statement; 5public class Stopwatch implements TestRule { 6private final Stopwatch stopwatch = new Stopwatch(); 7public Statement apply(Statement base, Description description) { 8return statement(base, description); 9} 10private Statement statement(final Statement base, Description description) { 11return new Statement() { 12public void evaluate() throws Throwable { 13Stopwatch.this.before(); 14try { 15base.evaluate(); 16} finally { 17Stopwatch.this.after(); 18} 19} 20}; 21} 22protected void before() throws Throwable { 23System.out.println("before test execution"); 24} 25protected void after() { 26System.out.println("after test execution"); 27} 28}29package com.javatpoint; 30import org.junit.Rule; 31import org.junit.Test; 32public class TestStopwatch { 33public Stopwatch stopwatch = new Stopwatch(); 34public void test1() { 35System.out.println("test1 executed"); 36} 37public void test2() { 38System.out.println("test2 executed"); 39} 40}
Stopwatch
Using AI Code Generation
1import org.junit.rules.Stopwatch;2import java.util.concurrent.TimeUnit;3@RunWith(Parameterized.class)4public class TestRunner {5 public Stopwatch stopwatch = new Stopwatch() {6 protected void finished(long nanos, Description description) {7 System.out.println(description.getDisplayName() + " finished in " +8 TimeUnit.NANOSECONDS.toMillis(nanos) + " ms");9 }10 };11 public static Collection<Object[]> data() {12 return Arrays.asList(new Object[][]{13 {1, 2, 3}, {2, 3, 5}, {3, 4, 7}14 });15 }16 private int a, b, c;17 public TestRunner(int a, int b, int c) {18 this.a = a;19 this.b = b;20 this.c = c;21 }22 public void test() {23 assertEquals(c, a + b);24 }25}26test(1,2,3) finished in 0 ms27test(2,3,5) finished in 0 ms28test(3,4,7) finished in 0 ms29import org.junit.Rule;30import org.junit.Test;31import org.junit.rules.TemporaryFolder;32import java.io.File;33import java.io.IOException;34import static org.junit.Assert.assertTrue;35public class TestRunner {36 public TemporaryFolder folder = new TemporaryFolder();37 public void testUsingTempFolder() throws IOException {38 File createdFolder = folder.newFolder("newfolder");39 File createdFile = folder.newFile("myfilefile.txt");40 assertTrue(createdFolder.exists());41 assertTrue(createdFile.exists());42 }43}44import org.junit.Rule;45import org.junit.Test;46import org.junit.rules.ErrorCollector;47import static org.hamcrest.CoreMatchers.is;48import static org.hamcrest.CoreMatchers.notNullValue;49import static org.junit.Assert.assertThat;50public class TestRunner {
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!