Spring test使用

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// 修改启动类,使用Spring的测试启动类
@RunWith(SpringJUnit4ClassRunner.class)
// 加载配置文件,否则无法注入
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
//junit 5
//@SpringJUnitConfig(locations = {"classpath:applicationContext.xml"})
public class AccountTest {

    @Autowired
    JdbcTemplate jdbcTemplate;

    ApplicationContext ctx;
    JdbcTemplate jdbcTemplate2;

    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate2 = ctx.getBean("jdbcTemplate", JdbcTemplate.class);
    }


    @Test
    public void Account_t1() {
        String sql = "select balance from account where name = ?";
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class, "sivan");
        System.out.println(integer);
    }

    @Test
    public void Account_t2() {

        String sql = "select balance from account where name = ?";
        Integer integer = jdbcTemplate2.queryForObject(sql, Integer.class, "sivan");

        System.out.println(integer);
    }


}
posted @ 2020-08-26 01:35  宁川  阅读(432)  评论(0)    收藏  举报