Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit base test auto setUp

I'd like to write a BaseTest class that simply provides a "universal setUp() method" for all extending subclasses:

public class BaseTest {
    @Before
    public void setUp() {
        System.out.println("setUp() was called!");

        // Doesn't really matter what this is doing...
        EnvironmentConfigurator.configureEnvForTesting();
    }
}

Then:

public class WidgetTest extends BaseTest {
    @Test
    public void test1() {
        fail();
    }

    @Test
    public void test2() {
        fail();
    }
}

So ideally, every time a subclass method annotated by @Test is executed, JUnit would first call the BaseTest#setUp() method, which does whatever (doesn't really matter). Perhaps its resetting some mock states to an initial value so that each test can start on a "clean slate", etc. Again, doesn't really matter.

Unfortunately when I run this code, I only see setUp() was called! printing to the screen once, so clearly BaseTest isn't "wrapping" my @Test methods the way I want. Is there any way to achieve this? Thanks in advance!

like image 941
IAmYourFaja Avatar asked Jan 02 '13 14:01

IAmYourFaja


People also ask

How do I run JUnit tests automatically?

To run JUnit 5 tests from Java code, we'll set up an instance of LauncherDiscoveryRequest. It uses a builder class where we must set package selectors and testing class name filters, to get all test classes that we want to run.

Does Setup run before every test?

The @BeforeClass methods of superclasses will be run before those the current class. The difference being that setUpBeforeClass is run before any of the tests and is run once; setUp is run once before each test (and is usually used to reset the testing state to a known-good value between tests).

Is JUnit automated?

Besides manual testing, JUnit is preferred equally for automation testing. It can also be used along with the Selenium WebDriver to automate tests for web applications. It provides a unique way to write structured, short, and better test cases.

What is setup method in JUnit?

First, JUnit 4 has a setup method that is invoked before each test method. This method is typically used for creating and configuring the system under test. This means that: We should create the dependencies of the tested object in this method.


1 Answers

I just ran this and both test methods are called and both times setUp is called.

If you have a @Before annotated method in the derived class as well then you will need to name the base class setup method to something different e.g. setUpBase() because if the method names are the same only the @Before annotated method in the derived class is called as it would be overriding the method in the base class.

like image 160
blank Avatar answered Oct 05 '22 13:10

blank