As you know any Maven project has main
and test
folders.
Keep all your code in main
except the actual tests that should be in test
.
Group tests/test classes and keep them in different packages especially if you have to cover several web services - see the example picture.
Root package
The root package for our framework project should be something like this com.xyz.checkout.test
. Usually this is the root package for the service plus test
.
SpringBootApplication class
Create your SpringBootApplication
class in the root package of the main
folder, in our case the class name will be CheckoutTestContext
(see the example picture).
That class will create the Spring context. Just create and forget about it - most likely you will never touch it.
package com.xyz.checkout.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CheckoutTestContext {
public static void main(String[] args) {
SpringApplication.run(CheckoutTestContext.class, args);
}
}
TestNG Test Class
@SpringBootTest(classes = CheckoutTestContext.class)
public class TestNGTestsWithSpringBootIT extends AbstractTestNGSpringContextTests {
@Test
public void simpleTest() {
Assert.assertEquals(2 * 2, 4, "2x2 should be 4");
}
}
You can put all that scary Spring stuff into BaseIT
@SpringBootTest(classes = CheckoutTestContext.class)
public class BaseIT extends AbstractTestNGSpringContextTests {
// Common methods, variables and constants
}
and extend it in your actual test classes
public class BillingAddressIT extends BaseIT {
@Test
public void simpleTest() {
Assert.assertEquals(2 * 2, 4, "2x2 should be 4");
}
}
JUnit Test Class
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CheckoutTestContext.class)
public class ShippingAddressIT {
@Test
public void twoPlusTwoTest() {
assertEquals(4, 2 + 2);
}
}
BaseIT class looks like this
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CheckoutTestContext.class)
public class BaseIT {
// Common methods, variables and constants
}
The test class that extends BaseIT
public class ShippingAddressIT extends BaseIT {
@Test
public void twoPlusTwoTest() {
assertEquals(4, 2 + 2);
}
}