springboot web高階(四) 單元測試

2022-02-12 03:17:36 字數 2057 閱讀 5146

基礎知識,參考:

1.入門測試類

最重要的不要忘記類上面的依賴,以及類裡面方法上的@test(底層是junit)

package

com.example.demo;

import

com.example.demo.service.girlservice;

import

org.junit.assert;

import

org.junit.test;

import

org.junit.runner.runwith;

import

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

import

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

import

org.springframework.test.context.junit4.springrunner;

/*** girlservice測試類

// 為了高大上一點,請不要再使用小白式的sout了,多使用斷言.

2.使用idea自動生成測試類

例如還是測試上面的service裡的findone,則通過在方法上右擊->goto->test

3.controller的api單元測試

同樣,在方法上右擊,goto->test,得到測試類

package

com.example.demo.controller;

import

import

org.junit.test;

import

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

import

org.springframework.boot.test.autoconfigure.web.servlet.autoconfiguremockmvc;

import

org.springframework.test.web.servlet.mockmvc;

import

org.springframework.test.web.servlet.request.mockmvcrequestbuilders;

import

org.springframework.test.web.servlet.result.mockmvcresultmatchers;

import

static org.junit.assert.*;

@autoconfiguremockmvc

public

class girlcontrollertest extends

@autowired

private

mockmvc mvc;

@test

public

void getlist() throws

exception

}

使用單元測試還有乙個用處是在打包是會自動跑單元測試,並會給出測試結果,失敗時將會報error!還有其他測試選項,例如測試.content.string("abc"來測試返回內容),完整的api,參考:這裡

Springboot web頁面404問題

使用springboot新建的web專案,介面可以正常訪問。但是h5頁面卻一直404.經過一段時間的探索,springboot中有著約定的設定,靜態資源在統一放在static目錄下包括靜態頁面和靜態資源 css等 動態模板放在templates目錄下。因此,要想訪問html頁面,第一種方式 把頁面放...

SpringBoot web載入位址預設跳轉設定

我們在設定完springboot專案之後,需要讓他預設跳轉乙個位址,需要怎麼做呢?答案很是簡單,可以通過springboot web的configuration配置,把預設的 路徑的路由,轉換為你想要指定的controller的view跳轉位址就行了。首先我們需要先構造乙個主頁的controller...

SpringBoot Web開發 訪問靜態資源

webmvcauotconfiguration類下的addresourcehandlers 方法 就是新增資源對映 resourceproperties 設定和靜態資源有關的引數,如快取時間等 webjars 以jar包的方式引入靜態資源 引入webjars依賴 我們可從webjars 找到我們想要...