Java Learning (eight) __SPRING2.5+JUNIT4 unit test

Source: Internet
Author: User
Tags rollback

Requirements:

JDK1.5 (because JUNIT4 is implemented with annotations)

the package you need

Spring-2.5.jar

Junit-4.4.jar

Spring-test.jar

Test Class

Package user;

Import static org.junit.Assert.fail;

Import Java.util.Date;

Import Org.junit.After;
Import Org.junit.Before;
Import Org.junit.Ignore;
Import Org.junit.Test;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.test.annotation.Rollback;
Import org.springframework.test.context.ContextConfiguration;
Import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
Import org.springframework.test.context.transaction.TransactionConfiguration;

Import Com.sample.model.user.User;
Import Com.sample.service.user.IUserService;


/** set the configuration file to load * *
@ContextConfiguration (
locations={
"Classpath:spring/persistencecontext.xml",
"Classpath:spring/aopcontext.xml",
"Classpath:spring/daocontext.xml",
"Classpath:spring/servicecontext.xml"
}
)

/** set whether to roll back the data * *
@TransactionConfiguration (Defaultrollback = False)

public class Usertest extends abstracttransactionaljunit4springcontexttests{

/** set the properties for automatic injection.
@Autowired
Private Iuserservice UserService;


@Before
public void SetUp () throws Exception {
}

@After
public void Teardown () throws Exception {
}

@Test
@Rollback (False)
public void Testsaveuser () {

User User=new user ();
User.setusername ("Zhoujun");
User.setcreatetime (New Date ());

Userservice.saveuser (user);

}

@Test
public void Testgetuserbyid () {

User User=userservice.getuserbyid ("1");

System.out.println (User.getusername ());
System.out.println (User.getcreatetime ());

}

}

the annotations in the JUNIT4 are described below:

@ContextConfiguration is used to specify the location of the loaded spring configuration file, the default configuration file is loaded

Examples of loading: classpath:/com/example/mytest-context.xml files

Package com.example;

@ContextConfiguration public
class MyTest {
    //class body ...
}

@ContextConfiguration annotation has the following two commonly used properties: locations: You can specify the location of the spring configuration file manually by using this property, and you can specify one or more spring configuration files. As shown below:
@ContextConfiguration (locations={"Xx/yy/beans1.xml", "Xx/yy/beans2.xml"}) Inheritlocations: Do you want to inherit Spring from the parent test case class Configuration file, the default is true. As in the following example:

@ContextConfiguration (locations={"Base-context.xml"}) public
 class Basetest {
     //...
 }
 @ContextConfiguration (locations={"Extended-context.xml"}) public
 class Extendedtest extends Basetest {
     // ...
 }

If Inheritlocations is set to False, Extendedtest only uses the Extended-context.xml configuration file, otherwise the base-context.xml and Extended-context.xml these two configuration files.

You must use @runwith (Springjunit4classrunner.class) before using all annotations to run the test in the spring test environment

The spring Framework provides commonly used spring-specific annotation sets in the Org.springframework.test.annotation package, and can be used in tests if you develop them in Java5 or above.

@IfProfileValue

Note that the annotation test is for a specific test environment only. This test can be started if the configured Profilevaluesource class returns the name value of the corresponding provider. This annotation can be applied to either a class or a separate method.

@IfProfileValue (name= "Java.vendor", Value= "Sun Microsystems Inc.")
public void Testprocesswhichrunsonlyonsunjvm () {
Some logic that should run only on the Java VMs from Sun Microsystems
}
At the same time, @ifprofilevalue can configure a list of values (using or semantics) to obtain TESTNG test group support in a JUnit environment. Look at the following example:

@IfProfileValue (name= "test-groups", values={"unit-tests", "integration-tests"})
public void Testprocesswhichrunsforunitorintegrationtestgroups () {
Some logic that should run is for the unit and integration test groups
}
@ProfileValueSourceConfiguration

Class-level annotations specify which profilevaluesource to use when obtaining configured profile values through @ifprofilevalue annotations. If @profilevaluesourceconfiguration is not declared in the test, the Systemprofilevaluesource is used by default.

@ProfileValueSourceConfiguration (Customprofilevaluesource.class)
public class Customprofilevaluesourcetests {
Class body ...
}
@DirtiesContext

When this annotation appears on the test method, it indicates that the underlying spring container is "contaminated" in the execution of the method, and must be recreated after the method execution ends, regardless of whether the test passed.

@DirtiesContext
public void Testprocesswhichdirtiesappctx () {
Some logic that results in the Spring container being dirtied
}
@ExpectedException

Indicates that the annotated method expects an exception to be thrown in execution. The type of the expected exception is given in the annotation. If an instance of the exception is thrown in the execution of the test method, the test passes. Similarly, if the exception instance is not thrown when the test method executes, the test fails.

@ExpectedException (Somebusinessexception.class)
public void Testprocessrainydayscenario () {
Some logic that should result in a Exception being thrown
}
@Timed

Indicates that the test method being annotated must be performed within the specified time interval (in milliseconds). If the test execution time exceeds the specified time interval, the test fails.

Note that the time interval includes the execution of the test method itself, any duplicate tests (see @Repeat), and any test fixture set up or tear down time.

Spring's @timed annotation with JUnit 4 's @test (timeout= ...) Support has different semantics. In particular, since JUnit 4 handles test execution timeouts, such as by executing test methods in a separate thread, it is not possible to use JUnit @test (timeout= ...) on test methods in one transaction context. Configuration. Therefore, if you want to configure a test method to be timed and transactional, you must jointly use spring's @timed and @transactional annotations. It is also noteworthy that @test (timeout= ...) The test method itself, if exceeded, will fail immediately, but @Timed focus on the total time of the test execution (including build and destroy operations and duplicates), and will not fail the test.

@Timed (millis=1000)
public void Testprocesswithonesecondtimeout () {
Some logic that should not take longer than 1 second to execute
}
@Repeat

Indicates that the test method being annotated must be executed repeatedly. The number of executions is declared in the note.

Note that the repeated execution scope includes the execution of the test method itself, as well as any test fixture set up or tear down.

@Repeat (10)
public void testprocessrepeatedly () {
...
}


@Rollback

Indicates whether the transaction of the annotated method needs to be rolled back after it completes. If true, the transaction is rolled back or the transaction is committed. Use the @rollback interface to override the default rollback flag for a configuration at the class level.

@Rollback (False)
public void Testprocesswithoutrollback () {
...
}
@NotTransactional

This annotation indicates that the test method must not be performed in a transaction.

@NotTransactional
public void Testprocesswithouttransaction () {
...
}

The Spring TestContext Framework also supports these non test-specific annotations and keeps their semantics unchanged. @Autowired @Qualifier @Resource (javax.annotation) if JSR-250 available @PersistenceContext (javax.persistence) If JPA is available @ Persistenceunit (javax.persistence) If JPA is available @Required @Transactional

@TestExecutionListeners

Defines the class-level metadata that Testexecutionlisteners uses Testcontextmanager for registration. Usually, @TestExecutionListeners will be used with @contextconfiguration.

@ContextConfiguration
@TestExecutionListeners ({customtestexecutionlistener.class, Anothertestexecutionlistener.class}) Public
class Customtestexecutionlistenertests {
    //class body ...
}

@TransactionConfiguration

Class-level metadata is defined for configuring a transactional test. In particular, if the desired platformtransactionmanager is not "TransactionManager", then the Platformtransactionmanager bean name of the driver transaction can be explicitly configured. In addition, you can change the DEFAULTROLLBACK flag to false. Usually, the @TransactionConfiguration is used in combination with @contextconfiguration.

@ContextConfiguration
@TransactionConfiguration (transactionmanager= "Txmgr", Defaultrollback=false)
public class Customconfiguredtransactionaltests {
    //class body ...
}

@BeforeTransaction
Indicates that the public void method being annotated should be executed before the transaction of the test method is started, and the transaction is configured by @transactional annotations.

@BeforeTransaction public
void Beforetransaction () {
    //logic to being executed before a transaction is started
}

@AfterTransaction

Indicates that the public void method being annotated should be executed after the end of the transaction of the test method, which is configured by @transactional annotations.

@AfterTransaction public
void Aftertransaction () {
    //logic to is executed after a transaction has ended
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.