詳解SpringBoot之新增單元測試

2022-09-29 23:03:26 字數 2061 閱讀 1002

在springboot裡新增單元測試是非常簡單的一件事,我們只需要新增springboot單元測試的依賴jar,然後再新增兩個註解就可搞定了。

首先我們來新增單元測試所需要的jar

org.springframework.boot

spring-boot-starter-test

接著我們寫了乙個單元測試的demo

package com.zkn.learnspringboot.service.test;

import com.zkn.learnspringboot.firstexample;

import com.zkn.learnspringboot.service.personservice;

import org.junit.test;

import org.junit.runner.runwith;

import org.springframework.beans.factory.annotation.autowired;

import org.springfra程式設計客棧mework.boot.test.context.springboottest;

import org.springframework.test.context.junit4.springjunit4classrunner;

/**

* created by wb-zhangkenan on 2016/11/18.

*/ @runwith(springjunit4classrunner.class)

@springboottest(classes = firstexample.class)

public class testsebmgrjktwrvice extends basetestservice

}然後我們run一下,乙個單元測試就搞定了。

另外:@runwith和@sprintboottest這兩個註解上都有@inherited這個註解,所以我們可以定義乙個單元測的父類,然後所有的單元測試類繼承這個父類就行了。如下所示:

package com.zkn.learnspringboot.service.test;

import com.zkn.learnspringboot.firstexample;

import org.junit.runner.runwith;

import org.springframework.boot.test.context.springboottest;

import org.springframework.test.context.junit4.springjunit4classrunner;

/**

* created by zkn on 2016/11/20.

*/ @runwith(springjunit4classrunner.class)

@springboottest(classes = firstexample.class)

public class basetestservice

package com.zknwww.cppcns.com.learnspringboot.service.test;

import com.zkn.learnspringboot.service.personservice;

import org.junit.test;

import org.springframework.beans.factory.annotation.autowired;

/**

* created by wb-zhangkenan on 2016/11/18.

*/ public class testservice extends basetestservice

}如果你用的springboot是1.4.0之前的話,所用的註解稍有不同。你需要把@springboottest註解換成@springapplicationconfiguration和@webappconfiguration。

本文標題: 詳解springboot之新增單元測試

本文位址: /ruanjian/j**a/197294.html

SpringBoot之新增單元測試

org.springframework.boot spring boot starter test test junit junit 4.10 org.springframework.boot spring boot test 2.0.3.release 寫了乙個單元測試的demo packagec...

springboot新增日誌

pom.xml新增依賴如下 org.springframework.boot spring boot starter web org.springframework.boot spring boot starter logging org.springframework.boot spring bo...

SpringBoot新增Swagger配置

swagger 是乙個規範和完整的框架,用於生成 描述 呼叫和視覺化 restful 風格的 web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法 引數 模型緊密整合到伺服器端的 允許api來始終保持同步。swagger 讓部署管理和使用功能強大的api從未如此簡單。1...