美文网首页
Spring boot 编写单元测试的流程

Spring boot 编写单元测试的流程

作者: 柳源居士 | 来源:发表于2019-03-26 23:12 被阅读0次

编写单元测试,需要用到Junit,spring 集成了Junit的工具包,因此,测试变得比较简单。
一个简单的测试程序,可以分为几个步骤:

  1. 创建spring 的application context。
  2. 声明该application context需要从何处加载配置文件
  3. 编写测试类。

以下为测试一个组件扫描是否工作正常的Junit代码:

package com.mingpin.yinuo.soundsystem;

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.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull(){
        assertNotNull(cd);
    }
}
package com.mingpin.yinuo.soundsystem;

import org.springframework.stereotype.Component;

@Component
public class Beyound implements CompactDisc {
    String title="光辉岁月";
    String artist="Beyound ";

    public void play() {
        System.out.println("Playing"+title+" by "+artist);
    }
}

package com.mingpin.yinuo.soundsystem;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {
}

package com.mingpin.yinuo.soundsystem;

public interface CompactDisc {
    void play();
}

此测试程序,测试了@ComponentScan是否工作正常。
@Autowired注解的bean是否能被正确的创建。

相关文章

网友评论

      本文标题:Spring boot 编写单元测试的流程

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