7 在Spring 5中使用JUnit

2019-03-05  本文已影响0人  See5170

步骤:

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.编写单元测试程序

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

结果

上一篇下一篇

猜你喜欢

热点阅读