Is it possible to place the setup/teardown methods using JUnit framework in a single class (which would be my baseclass) so on test runs they methods are always called first/last? it would be in a similar way to which nunit tests can be structured
currently the only way I can get my tests to kick off is if I have the setup/teardown methods within the same class as my tests are (which is something I wan't to avoid, to keep my test classes tidy)
example I would hope to set up;
public class baseclass
{
#Before
public void setUp
{}
#After
public void tearDown
{}
}
public class tests
{
#Test
public void test1
{
// test content here
}
}
Run this test and see the sequence of events
class Test1 {
#Before
public void setUp1() {
System.out.println("setUp1");
}
}
public class Test2 extends Test1 {
#Before
public void setUp2() {
System.out.println("setUp2");
}
#Test
public void test() {
System.out.println("test");
}
}
Yes, as long as your test class extend your baseclass.
For instance:
Suite
#RunWith(Suite.class)
#SuiteClasses(Tests.class)
public class AllTests {
}
BaseClass
public class BaseClass {
#BeforeClass
public static void beforeAll() {
}
#Before
public void setUp() {
}
#After
public void tearDown {
}
#AfterClass
public static void afterAll() {
}
}
Tests
public class Test extends BaseClass {
#Test
public void test1() {
}
#Test
public void test2() {
}
}
Related
I tried to write test for my spring boot application.
My application has business logic, which start after spring app has been initialized.
There is need to test triggeration of method with annotation #EventListener(ApplicationReadyEvent.class)
Below is a simple example that doesn't work. I expect that inscription "Testing..." appears in the console.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {
MySpringBootTest.MyTestConfig.class
})
public class MySpringBootTest {
#Test
public void test() {
}
#Configuration
public static class MyTestConfig {
#EventListener(ApplicationReadyEvent.class)
public void init() {
System.out.println("Testing...");
}
}
}
how do I make this example work?
Because you are using #ContextConfiguration Spring application Context is partially loaded and you don't have access to every capability of Spring application Context, however There are many ways to achieve something you want to do. One of them is using TextExecutionListener. I will show you how to use that in both Junit 4 and Junit 5 (jupiter):
Junit 5 (jupiter):
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes= MySpringBootTest.MyTestConfig.class)
#TestExecutionListeners(listeners = {MySpringBootTest.MyTestConfig.class})
public class MySpringBootTest {
#Test
public void test1() {
....
}
#Test
public void test2() {
...
}
#Configuration
public static class MyTestConfig extends AbstractTestExecutionListener {
#Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("Testing...");
testContext.getApplicationContext(); //Do anything you want here
}
}
}
Here is a quote from Java doc for beforeTestClass method of TestExecutionListener:
Pre-processes a test class before execution of all tests within
the class. This method should be called immediately before
framework-specific before class lifecycle callbacks.
From the testContext that will be passed to this method you will have access to the application context and test class itself, you can do every thing you want with the test class there.
Junit 4:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {MySpringBootTest.MyTestConfig.class})
#TestExecutionListeners(listeners = {MySpringBootTest.CustomTestExecutionListener.class,
SpringBootDependencyInjectionTestExecutionListener.class})
public class MySpringBootTest {
#Test
public void test1() {
....
}
#Test
public void test2() {
...
}
#Configuration
public static class MyTestConfig {
}
public static class CustomTestExecutionListener extends AbstractTestExecutionListener {
#Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("Testing...");
testContext.getApplicationContext(); //Do anything you want here
}
}
}
So I am trying to run JUnit parameterized tests along with non-parameterized tests in the same test class. But I am running into one error or the other. Has anyone tried this before and were they successful in doing so? I know other runners need to be used with the #PowerMockRunnerDelegate in order to run correctly. So here's what I came up with:
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(Enclosed.class)
#PrepareForTest(Some.class)
#PowerMockIgnore("javax.management.*")
public class TestClass {
#PowerMockRunnerDelegate(Parameterized.class)
public static class ParameterizedTests {
}
#Test
public void nonParameterizedTestOne() {
}
#Test
public void nonParameterizedTestTwo() {
}
}
But I get the error:
Test class should have exactly one public zero-argument constructor
Without powermock, this situation can be easily handled with:
#RunWith(Enclosed.class)
public class TestClass {
#RunWith(Parameterized.class)
public static class ParameterizedTests {
}
#Test
public void nonParameterizedTestOne() {
}
#Test
public void nonParameterizedTestTwo() {
}
}
But I would definitely like to use powermock. Any solutions?
I had the same issue, this worked for me:
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(Enclosed.class)
#PrepareForTest({Some.class})
public class TestClass {
private static void setUpOnceForAllTests() {
}
private static void setUpForEveryTest() {
}
public static class SingleTests {
// Setup once for all single tests
#BeforeClass
public static void setUpBeforeClass() {
setUpOnceForTests();
}
// Setup for each and every single test
#Before
public void setUp() {
setUpForEveryTest();
}
#Test
public void nonParameterizedTestOne() {
}
#Test
public void nonParameterizedTestTwo() {
}
}
#PowerMockRunnerDelegate(Parameterized.class)
public static class ParameterizedTests {
// Setup once for all parameterized test
#BeforeClass
public static void setUpBeforeClass() {
setUpOnceForTests();
}
// Setup for each and every parameterized test
#Before
public void setUp() {
setUpForEveryTest();
}
#Parameterized.Parameters
public static Collection<Enum> param() {
return new ArrayList<>(Arrays.asList(Enum.values()));
}
#Parameterized.Parameter
public int param;
#Test
public void parameterizedTestOne() {
}
#Test
public void parameterizedTestTwo() {
}
}
}
How can I share an ExternalResource between two classes in a junit test suite?
TestSuite.java
#RunWith(Suite.class)
#SuiteClasses({ TestA.class, TestB.class })
public class TestSuite {
#ClassRule
public static MyResource res = new MyResource();
}
MyResource is an ExternalResource and I want to access res in the test suite classes TestA and TestB.
TestA.java
public class TestA {
#Test
public void testA() {
System.out.println("####### testA");
// res.someGetMethod();
}
}
TestB.java
public class TestB {
#Test
public void testB() {
System.out.println("####### testB");
// res.someGetMethod();
}
}
Thanks for looking.
The ClassRules of the Suite are shared and accessible from its TestCases, it will intialised before the test case, and hence you can access it as you do with any public static variable
#Test
public void testA() {
System.out.println("####### testA");
TestSuite.res.someGetMethod();
}
I have TestNG tests in some classes, which extends the same main class.
I need the same last test for class1 and class2, but if I add #Test(priority = 666) to main class it start after all classes.
How I should annotate #Test in main class what would it starts after all tests of each class?
Big thanks. Also sorry for bad english.
main class
public class MainTest {
#BeforeClass()
public void setup() {
//something
}
#AfterClass()
public void tearDown() {
//something
}
#AfterMethod()
public void log_writer(Method method) {
//something
}
#Test(priority = 666) {}
}
class1
public class Class1 extends MainTest {
#Test
public void test1(){}
#Test
public void test2(){}
}
and class2
public class Class2 extends MainTest {
#Test
public void test1(){}
#Test
public void test2(){}
}
what you are looking for is the #AfterClass annotation. handle the part where you want to check logs in the AfterClass annotated method
It's not possible. Basically each #Test runs only once. If you need to do something after each test class you have to use #AfterClass annotation on method in your MainTest. You can do some hacks with method order etc. in MethodInterceptor (http://testng.org/doc/documentation-main.html#methodinterceptors) but it's not good idea for this case.
For example:
#RunWith(MockitoJUnitRunner.class)
public class ClientFormServiceTest {
#Mock
ClientFormService clientFormService;
public class GetNewClientFormTest {
#Mock
protected ClientForm result;
#Before
public void given() {
result = clientFormService.getNewForm();
}
#Test
public void should_do_something() {
}
}
public class CreateClientFormTest {
#Mock
protected ClientForm clientForm;
#Before
public void given() {
clientFormService.createForm(clientForm);
}
#Test
public void should_do_something() {
}
}
}
This is what I want to do but I can't run the unit tests if are nested to a class.
I'm the author of a JUnit TestRunner, junit-nested, which I believe may do what you want: https://github.com/avh4/junit-nested
However, from your example it's not clear why you need nested tests. The typical reason to use them is to share setup behavior, but you should consider if having separate test classes is more appropriate.
In any case, here's how you can do it with junit-nested: (Since Nested is a test runner, you'll have to use MockitoAnnotations.initMocks() instead of the Mockito test runner.)
import net.avh4.test.junit.Nested;
#RunWith(Nested.class)
public class ClientFormServiceTest {
#Mock
ClientFormService clientFormService;
#Before
public void given() {
MockitoAnnotations.initMocks(this);
}
public class GetNewClientFormTest {
#Mock
protected ClientForm result;
#Before
public void given() {
MockitoAnnotations.initMocks(this);
result = clientFormService.getNewForm();
}
#Test
public void should_do_something() {
}
}
public class CreateClientFormTest {
#Mock
protected ClientForm clientForm;
#Before
public void given() {
MockitoAnnotations.initMocks(this);
clientFormService.createForm(clientForm);
}
#Test
public void should_do_something() {
}
}
}
Why would you like to do that? If you mean to benefit from code reuse among many similar tests, you could come up with a base test class with common code and make test classes extend it.