Springboot 的单元测试

1 测试基础类

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = { POSApplicationRunner.class})
public class BaseSpringTester {
}
  • POSApplicationRunner.class 为项目启动类
  • 两个注解即可

2 单个功能类的单元测试

public class ReceiptTest extends BaseSpringTester {

    private final static Gson gson = new Gson();


    @Autowired
    private PosConfigService posConfigService;

  
    @Test
    public void saveReceiptConfigTest() {
        PosBaseConfigEntity entity = new PosBaseConfigEntity();
        entity.setShopId(1L);
        entity.setStaffId(3L);
        entity.setIsUsedPrint(1);
        entity.setReceiptTitle("ucan西湖广场店");
        entity.setReceiptEnd("谢谢惠顾\n" +
                "咨询电话:021-61671638\n" +
                "地址:上海市长宁区遵义路100号南丰城3f南区l307\n" +
                "ok");
        entity.setReceiptLineSpacing(3);
        entity.setReceiptSize(1);
        posConfigService.updatePosSystemPortConfig(entity);
    }
 }    
  • 和普通的方法调用一样注入,自己模拟数据,测试每个接口的方法

3 引入jar包

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

附加一个POSApplicationRunner


@EnableEurekaClient
@EnableConfigurationProperties
@EnableWebMvc
@EnableScheduling
@EnableAsync
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        MongoAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
})
@EnableTransactionManagement
@EnableHystrix
@EnableHystrixDashboard
@EnableFeignClients(basePackages = "com.mamahao.ebiz.pos.web.microservice")
@ComponentScan(value = {"com.mamahao.ebiz.pos"})
public class POSApplicationRunner implements CommandLineRunner {
 
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(POSApplicationRunner.class);
        application.setRegisterShutdownHook(true);
        application.run(args);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                //logger.info("******************************mamahao-ebiz-pos shutdown******************************");
            }
        });
    }

    @Override
    public void run(String... args) throws Exception {
        //logger.info("******************************mamahao-ebiz-pos startup******************************");
    }

}

 

posted @ 2018-07-31 15:21  谢幕ゾ华丽  阅读(474)  评论(0编辑  收藏  举报