Posts

Showing posts from June, 2021

Java - Writing your own JUnit Rule

 Repost from  https://medium.com/@vanniktech/writing-your-own-junit-rule-3df41997b10c A JUnit Rule can be used to do some work around the execution of a test. One example would be to set up something before a test is running and then after it ran tearing something down. This is actually quite simple to do with JUnit itself. public class YourTest { @Before public void setUp() { // Do something before exampleTest starts. } @Test public void exampleTest() { // Your normal test. } @After public void tearDown() { // Do something after exampleTest finished. } } Now imagine you want to connect to a database during  setUp  and then close the connection in  tearDown . If you want to use that database in multiple files you don’t want to copy paste that code in every file. TestRule Let’s look at a quick example of a custom TestRule. public final class DatabaseRule implements TestRule { public Database database; @Override public Statement apply(f...