Spring中使用JUnit Test

在pom.xml添加test依赖


      junit
      junit
      4.12
      test
    
      
        org.springframework
        spring-context
        ${spring.version}
      
    
    
      org.springframework
      spring-test
      ${spring.version}
    

以Max类比较大小为例

Max类

package com.spring.IoC;

/**
 * Created by User on 2019/3/4.
 * 待测程序,求两个数的较大值
 */
public class Max {
    private int a;
    private int b;

    public Max(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int getMax(){
        return a > b ? a : b;
    }
}

bean


    
        
        
    

将光标放在public class Max一行 快捷键“alt+enter” 选择 Creat Test


光标.png

选择.png

选择如图:


如图.png

自动生成MaxTest

package com.spring.IoC;

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 static org.junit.Assert.*;

/**
 * Created by User on 2019/3/4.
 */
//指定单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations = {"/spring.xml"})
public class MaxTest {
//    自动注入max(仓库管理给斧头)
    @Autowired
    private Max max;

    @Test
    public void getMax() throws Exception {
        assertEquals(5,max.getMax());
    }

}

你可能感兴趣的:(Spring中使用JUnit Test)