Rollback transaction after @Test

Just add @Transactional annotation on top of your test: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {“testContext.xml”}) @Transactional public class StudentSystemTest { By default Spring will start a new transaction surrounding your test method and @Before/@After callbacks, rolling back at the end. It works by default, it’s enough to have some transaction manager in the context. From: 10.3.5.4 Transaction … Read more

How do I manage unit test resources in Kotlin, such as starting/stopping a database connection or an embedded elasticsearch server?

Your unit test class usually needs a few things to manage a shared resource for a group of test methods. And in Kotlin you can use @BeforeClass and @AfterClass not in the test class, but rather within its companion object along with the @JvmStatic annotation. The structure of a test class would look like: class … Read more

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven’t prepared A? Try this: A.java public class A { private final String test; public A(String test) { this.test = test; } public String check() { return “checked ” + this.test; } } MockA.java import static org.hamcrest.MatcherAssert.assertThat; import … Read more

In JUnit 5, how to run code before all tests

This is now possible in JUnit5 by creating a custom Extension, from which you can register a shutdown hook on the root test-context. Your extension would look like this; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL; public class YourExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource { private static boolean started = false; @Override public void beforeAll(ExtensionContext context) { … Read more

JUnit 4 compare Sets

You can assert that the two Sets are equal to one another, which invokes the Set equals() method. public class SimpleTest { private Set<String> setA; private Set<String> setB; @Before public void setUp() { setA = new HashSet<String>(); setA.add(“Testing…”); setB = new HashSet<String>(); setB.add(“Testing…”); } @Test public void testEqualSets() { assertEquals( setA, setB ); } } … Read more