How to rollback a database transaction when testing services with Spring in JUnit?

You need to extend transaction boundaries to the boundaries of your test method. You can do it by annotating your test method (or the whole test class) as @Transactional: @Test @Transactional public void testInsert(){ long id=myService.addPerson(“JUNIT”); assertNotNull(id); if(id<1){ fail(); } } You can also use this approach to ensure that data was correctly written before … Read more

Testing an EJB with JUnit

The accepted answer requires mocking a lot of code, including the persistence layer. Use an embedded container to test the actual beans, instead; otherwise, mocking the persistence layer results in code that barely tests anything useful. Use a session bean with an entity manager that references a persistence unit: @Stateless public class CommentService { @PersistenceContext(unitName … Read more

Testing against Java EE 6 API

Not sure this will solve your problem but GlassFish Embedded provides a Java EE 6 implementation. Add this to your pom.xml: <project> … <repositories> <repository> <id>glassfish-extras-repository</id> <url>http://download.java.net/maven/glassfish/org/glassfish/extras</url> </repository> </repositories> … <dependencies> <dependency> <groupId>org.glassfish.extras</groupId> <artifactId>glassfish-embedded-all</artifactId> <version>3.0.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> … </dependencies> … </project> It’s important to declare the glassfish-embedded-all artifact before … Read more

Eclipse/Maven: JUnit tests not compiled when running them

I had the same problem with STS Eclipse (Spring development variant), m2e and JUnit. The solution was to set the output folder for src/test/java to target/test-classes: Right click the src/test/java folder in the Package Explorer Select Build Path -> Configure Output Folder Enter target/test-classes, click OK Now the changes in test classes are compiled correctly … Read more

Android RxJava 2 JUnit test – getMainLooper in android.os.Looper not mocked RuntimeException

This error occurs because the default scheduler returned by AndroidSchedulers.mainThread() is an instance of LooperScheduler and relies on Android dependencies that are not available in JUnit tests. We can avoid this issue by initializing RxAndroidPlugins with a different Scheduler before the tests are run. You can do this inside of a @BeforeClass method like so: … Read more

Spring not autowiring in unit tests with JUnit

Add something like this to your root unit test class: @RunWith( SpringJUnit4ClassRunner.class ) @ContextConfiguration This will use the XML in your default path. If you need to specify a non-default path then you can supply a locations property to the ContextConfiguration annotation. http://static.springsource.org/spring/docs/2.5.6/reference/testing.html