Spring jUnit Annotations :
Annotation | Package Detail/Import statement |
---|---|
@RunWith | import org.junit.runner.RunWith; |
@ContextConfiguration | import org.springframework.test.context.ContextConfiguration; |
@Test | import org.junit.Test; |
@DirtiesContext | import org.springframework.test.annotation.DirtiesContext; |
@Timed | import org.springframework.test.annotation.Timed; |
We are now ready to test our Spring based application using jUnit and Spring Unit testing framework. The following jUnit and Spring annotations will be used to accomplish this.
@RunWith
When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit. Let us configure jUnit to use Spring jUnit Class runner.
1
2
3
4
5
| @RunWith (SpringJUnit4ClassRunner. class ) @ContextConfiguration (locations = { "/spring-servlet-test.xml" }) public class CompanyServiceTest { ... } |
@ContextConfiguration
Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.
1
2
3
4
5
| @RunWith (SpringJUnit4ClassRunner. class ) @ContextConfiguration (locations = { "/spring-servlet-test.xml" }) public class CompanyServiceTest { ... } |
@ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default. |
@Test
Annotate all your jUnit unit tests with @Test. Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.
1
2
3
4
5
6
7
8
9
10
| @Autowired private CompanyService companyService; @Test public void testFindByName() { Company company = companyService.findByName( "techferry" ); if (company != null ) { assertEquals( "prospect" , company.getStatus().getName()); } } |
@DirtiesContext
Annotate @DirtiesContext to indicate that it dirties the ApplicationContext. This will trigger context reloading before execution of next test.@Timed
Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails.
1
| @Timed (millis= 1000 ) |
References
- Annotations for Unit Testing Spring applications: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations
No comments :
Post a Comment