[Junit] Spring loaded Spring container for unit testing (finishing)

Original Address: https://www.cnblogs.com/swugogo/p/5908435.html

Read catalog

> Introducing relevant Jar package

A, required introducing the desired package

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.10.RELEASE</version>
</dependency>

> Profiles loading

(A) loading a configuration file <original manual loading>

Context = the ApplicationContext new new a FileSystemXmlApplicationContext ( "the WebRoot / the WEB-INF / the applicationContext.xml" );
 new new the ClassPathXmlApplicationContext ( "the applicationContext.xml"); // load from the classpath 
new new a FileSystemXmlApplicationContext ( "classpath: Address"); // not represented classpath Current directory

(B) notes the way automatic loading

 @org.springframework.test.context.ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})
 
 @org.springframework.test.context.ContextConfiguration(locations={"classpath:applicationContext.xml"}) 
@RunWith (the SpringJUnit4ClassRunner. Class )   // use junit4 test   
    @ContextConfiguration    
    ({ "/spring/app*.xml","/spring/service/app*.xml"}) // load the configuration file   
      
    // --- --------- If adding the following code, the class inherits all test classes will follow this configuration, it may not be applied in the method for testing the class // / control transactions, see next example  
     // this very critical, if you do not join this annotation configuration, transaction control will be completely ineffective!  
    // @Transactional  
     // associated with a transaction where the transaction to the controller configuration file (transactionManager = "transactionManager"), while // specify automatic rollback (defaultRollback = true). Such operations do not pollute the data before the database!  
    // @TransactionConfiguration (transactionManager = "transactionManager", defaultRollback = to true)  
     //------------   
    public  class BaseJunit4Test {   
    }  

> Original usage

Test class which you want to set the Spring configuration (I am here "/config/application*.xml") is loaded, you can then injected into the bean container. Here are annotated with the way

package com.nicchagil.mybatis3spring3intg.junit;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.nicchagil.mybatis3spring3intg.bean.User;
import com.nicchagil.mybatis3spring3intg.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class JunitTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    public void c1() {
        List<User> userList = userService.query(new User());
        System.out.println(userList);
    }

}

In a specific test class, by way of manually loading a configuration file is JUnit tests, has the following disadvantages :

1) resulting in multiple initialization Spring container problem

2) requires the use of hard-coding retrieve another Bean, need to cast

3) scene database vulnerable to damage (the ideal state: automatic rollback of the database to ensure that the site database is not destroyed, so repeat the test problem does not occur)

4) is not convenient for checking the correctness of data manipulation (ideal state: jdbcTemplate had access to the database in the same transaction, change the query data, verify the correctness of operation)

 

> Common usage

Common way is to load the configuration of a part of a public out:

package com.nicchagil.mybatis3spring3intg.junit;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class BaseJunit {
    
}

Then each test class needs to inherit public classes:

Package com.nicchagil.mybatis3spring3intg.junit; 

Import java.util.List; 

Import org.junit.Test;
 Import org.springframework.beans.factory.annotation.Autowired; 

Import com.nicchagil.mybatis3spring3intg.bean.User;
 Import COM. nicchagil.mybatis3spring3intg.service.UserService; 

public  class UserServiceTest the extends BaseJunit { 
    
    @Autowired 
    Private UserService that userService; 
  @Resource // automatically injected, by default name   
  Private IBaseDao BaseDao; 

  @Test // indicated is the test method   
  @Transactional //This method requires the use of transaction indicated   
  @Rollback ( to false ) // After completion of this method using the indicated transaction is not rolled back, true when rollback   
  public  void C1 () { 
    List <the User> userList = userService.query ( new new the User ()) ; 
    System.out.println (userList); 
  } 
}
// Review: the difference @Autowired & @Resource
 // @Autowired annotations are fitted dependent objects by type, by default it requires dependent objects must be present, if the null value is allowed, it is required attribute can be set to false. If we want to use the assembly by name, it can be used together in combination @Qualifier comment. As follows: 
 //     @Autowired @Qualifier ( "personDaoBean") 
 //     Private the PersonDao PersonDao; 

// @Resource @Autowired as annotations and may be marked on the field or property setter method, but it is by default the name of the assembly. Name can be specified by the name attribute @Resource if no name attribute, when annotations marked on the field, the default field name taken as the bean name Looking dependent objects, when the annotation on annotation property setter methods, i.e. taking the default attributes Looking bean name as the name of dependent objects. 
//     @Resource (name = "personDaoBean") 
 //     Private the PersonDao the PersonDao; // for the field 

// Note: If you do not specify the name attribute, and still can not find dependent objects in accordance with the default name, @Resource annotations fall back by type assembly. But once the name attribute is specified, it is only by name equipped.

 

 

For example:

Tools: RestClientUtil.java
package com.kszsa.common.rest;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class RestClientUtil {
    /**
     * 调用远程Rest接口
     * @param url
     * @param classType
     * @param params
     * @param <T>
     * @return
     */
    public <T> T get(String url, Class<T> classType, Map<String,Object> params){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(url, classType, params);
    }
}

Test category

RestClientUtilTest.java
package com.kszsa.common.rest;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.HashMap;
import java.util.Map;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/*.xml"})
public class RestClientUtilTest {
    @Autowired
    private RestClientUtil restClientUtil;

    @Test
    public void get(){
        String url = "http://localhost:8080/ssht/user/get?id={id}";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",2);
        JSONObject jsonObject = restClientUtil.get(url, JSONObject.class, map);
        System.out.println(jsonObject);
    }


}

 

Guess you like

Origin www.cnblogs.com/dyh004/p/11584110.html