7 在Spring 5中使用JUnit

步骤:

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断言,判断期望值和实际值是否相等
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容