Spring has had a really nice unit test framework available for a while now, but the documentation can be a bit daunting. Here’s a super-simple example of adding dependency injection to an integration test:
Here’s .../src/main/resources/spring.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="bool" class="java.util.concurrent.atomic.AtomicBoolean"> <constructor-arg value="true"/> </bean> </beans>
And the .../src/test/java/.../ExampleTest.java:
import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Resource; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/spring.xml"}) public class ExampleTest { @Resource(name = "bool") private AtomicBoolean bool; @Test public void testBool() throws Exception { Assert.assertTrue(bool.get()); } }
Of course, the point would be to spin up hibernate or whatever other beans you have, rather than spending 50 lines to create a boolean reference.
Here’s the maven dependency (assuming you’re still on the 2.5.x branch)
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>2.5.6.SEC01</version> <scope>test</scope> </dependency>
Related posts:
- TestNG, test groups, IDEA, and @BeforeMethod
Say you have public class SomeTestNG { @BeforeClass public void setup() { … } @Test public void test1() { … } @Test public void test2() { … } } You’ll...... - Create new junit tests in Eclipse with a keystroke
The Galileo version of Eclipse doesn’t ship with a default keybinding for creating a unit test for the current class, but you can add one easily enough. Navigate to Preferences...... - Simple Log4J eclipse template
Do you use eclipse and log4j? Do you have a template to add a static Logger instance in classes? Do you have to manually add the import? HA! NO MORE!...... - Hibernate Naming Strategies
Using Hibernate annotations with the default naming strategy leaves you with camelCasedColumnNames in your database schema. Gavin King provided a good camelCase to underscore_separated naming strategy with org.hibernate.cfg.ImprovedNamingStrategy. The only......