美文网首页
7 在Spring 5中使用JUnit

7 在Spring 5中使用JUnit

作者: See5170 | 来源:发表于2019-03-05 10:31 被阅读0次

    步骤:

    1.添加依赖(spring-test依赖-junit依赖必不可少)

    <!--spring-test依赖-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!--junit依赖-->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
    
    

    2.编写待测程序(Max类)

    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;
        }
    }
    
    

    3.配置bean

        <!--定义bean-->
        <bean id="messageServiceImpl" class="com.spring.IoC.di.service.MessageServiceImpl">
            <constructor-arg name="username" value="Chen Yang"/>
            <constructor-arg name="age" value="20"/>
        </bean>
        <bean id="messagePrinter" class="com.spring.IoC.di.MessagePrinter">
            <constructor-arg name="service" ref="messageServiceImpl"/>
        </bean>
    
    

    4.编写单元测试程序

    • 光标放在待测试程序 利用快捷键alt+enter 选择Create Test

      image
    • 选择getMax():int

      image
    • 编写测试程序

    //指定单元测试环境
    @RunWith(SpringJUnit4ClassRunner.class)//反射
    //指定配置文件路径
    @ContextConfiguration(locations = {"/applicationContext.xml"})
    public class MaxTest {
        //自动注入max
        @Autowired
        private Max max;
        @Test
        public void getMax() {
            assertEquals(5,max.getMax());
        }
    }
    
    

    结果

    • @Autowired为自动注入
    • 使用assertEquals断言,判断期望值和实际值是否相等

    相关文章

      网友评论

          本文标题:7 在Spring 5中使用JUnit

          本文链接:https://www.haomeiwen.com/subject/sycnuqtx.html