码迷,mamicode.com
首页 > 编程语言 > 详细

JUnit整合Spring

时间:2020-07-12 01:13:35      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:package   context   one   end   pack   spring   update   app   junit单元测试   

1. 加入Spring-test依赖

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

2. 指定Spring的Runner方法

@RunWith(SpringJUnit4ClassRunner.class)

3. 指定主配置文件或主配置类

@ContextConfiguration(classes = Config.class)
或
@ContextConfiguration(locations = "classpath:bean.xml")

样例:

package com.example;

import com.example.config.Config;
import com.example.domain.Account;
import com.example.service.IAccountService;
import org.junit.Before;
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.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Spring整合JUnit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class AccountServiceTest {

    @Autowired
    IAccountService as;

    @Test
    public void testFindAll() {
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne() {
        Account account=as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave() {
        Account account=new Account("ddd",100);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate() {
        Account account=new Account(2,"ddd",100);
        as.updateAccount(account);
    }
    @Test
    public void testDelete() {
        as.deleteAccount(1);
    }
}

 

JUnit整合Spring

标签:package   context   one   end   pack   spring   update   app   junit单元测试   

原文地址:https://www.cnblogs.com/abuduri/p/13286072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!