1. 程式人生 > >【SpringBoot】Junit單元測試遇到的一些問題

【SpringBoot】Junit單元測試遇到的一些問題

情況 ①:不能有返回值

@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public String testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
        return "";
    }
}

報錯:

java.lang.Exception: Method testDownload() should be void

	at org.junit.runners.model.FrameworkMethod.validatePublicVoid(FrameworkMethod.java:99)
	at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:74)
	at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
	...

解決辦法:測試用例方法是不能有返回值的,必須是public void的

情況 ②:NullPointerException

@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}

報錯:

java.lang.NullPointerException 
	at com.yealink.version.controller.FileControllerTest.testDownload(FileControllerTest.java:20)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	...

解決辦法:意味著要在測試類頂部加上註解@RunWith(SpringRunner.class)

情況 ③:Bean注入失敗
@RunWith(SpringRunner.class)
@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}
報錯:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.yealink.version.controller.FileControllerTest': Unsatisfied dependency expressed through field 'fileController'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yealink.version.controller.FileController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
	at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yealink.version.controller.FileController' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
	... 27 common frames omitted

解決辦法:該錯誤意味著是注入失敗,需要在測試類頂部加上註解@SpringBootTest(classes =VersionManagerApplicationForDev.class),且這個啟動類(VersionManagerApplicationForDev)需要進行掃描,即在啟動類上加@SpringBootApplication註解。

情況 ④:找不到相應的啟動配置

@RunWith(SpringRunner.class)
@SpringBootTest(classes = VersionManagerApplicationForDev.class)
@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}

報錯:

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
	at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4420)
	...

解決辦法:這是因為我的專案中application.yml裡面進行了多環境配置,如果有的沒有相應的資料庫會報錯。因為可以在測試類頂部加上註解@ActiveProfiles("dev")選擇需要的環境。

情況 ⑤:優化

@RunWith(SpringRunner.class)
@SpringBootTest(classes = VersionManagerApplicationForDev.class)
@ActiveProfiles("dev")
@Controller
public class FileControllerTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}

可以看到如果有很多的測試類,那麼需要在每個測試類頂部加上這些註解也是很多餘的,因此可以寫成一個基類,讓測試類繼承基類即可,最後就變成了這樣:

public class FileControllerTest extends BaseTest{

    @Autowired
    private FileController fileController;

    @Test
    public void testDownload(){
        fileController.download("2dd4209286df4f14b703890ccdc3d2ff");
    }
}
import com.yealink.version.VersionManagerApplicationForDev;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by yl1794 on 2018/6/6.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = VersionManagerApplicationForDev.class)
@ActiveProfiles("dev")
public class BaseTest {

}

相關推薦

SpringBootJunit單元測試遇到的一些問題

情況 ①:不能有返回值@Controller public class FileControllerTest{ @Autowired private FileController fileController; @Test public S

解決Junit單元測試中出現的報錯

at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.de

Android進階Junit單元測試環境搭建以及簡單有用

rar theme 選擇 http 技術分享 才幹 ack package family 單元測試的目的 首先。Junit單元測試要實現的功能,就是用來測試寫好的方法是否可以正確的運行,一般多用於對業務方法的測試。 單元測試的環境配置 1.在Andro

node----mocha單元測試框架-----格爾尼卡ぃ

ins number ber moc tutorial ride 對象 單元測試框架 cal 一、mocha簡介 單元測試是用來對一個模塊、一個函數、或者一個類來進行正確性的檢測工作 特點: 既可以測試簡單的JavaScript函數,又可以測試異步代碼,

springBoot dubbo junit 單元測試

依賴   <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version> 4.12</versi

SpringBoot使用Junit單元測試

SpringBoot + mybatis 開發工具:IntelliJ IDEA 1.pom.xml 一般使用idea新建一個SpringBoot web專案時,一般都會自動引入此依賴,如果沒有,請手動引入。         

Spring Boot---(11)SpringBoot使用Junit單元測試

摘要:本文詳細的記錄了SpringBoot如何結合Junit寫測試用例,如何執行,打包執行,忽略執行等操作,SpringBoot內建了Junit測試元件,使用很方便,不用再單獨引入其他測試元件。 演示環境: SpringBoot + mybatis 開發工具:IntelliJ IDEA

C#xUnitMoq.NET單元測試Mock框架Moq初探!

在TDD開發模型中,經常是在編碼的同時進行單元測試的編寫,由於現代軟體開發不可能是一個人完成的工作,所以在定義好介面的時候我們就可以進行自己功能的開發(介面不能經常變更),而我們呼叫他人的功能時只需要使用介面即可。 但我們在編寫自己的單元測試並進行功能驗證的時候,如果介面的實現人還沒有完成程式碼怎麼

4spring單元測試和ApplicationContext區別

ApplicationContext 等於直接呼叫 public ClassPathXmlApplicationContext(String[] configLocations, boolean re

Pytestpython單元測試框架pytest簡介

1、Pytest介紹 pytest是python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高。根據pytest的官方網站介紹,它具有如下特點: 非常容易上手,入門簡單,文件豐富,文件中有很多例項可

QTQt單元測試淺析

Qt單元測試框架,使用於基於Qt的應用程式和庫,先從一個簡單的demo工程說起吧。我們可以通過QtCreator來建立一個簡單的Qt單元測試工程,夏天到了,這個demo工程的名字就叫Summer好了,建

SpringBootJunit單元測試

  最近做專案搭建的是springboot框架,springboot搭建的辛酸淚就不多說了,然而我們做專案單元測試是少不了的,然而這springboot專案怎麼搞單元測試?我呢個去!摸索了半個小時終

SpringBoot開發Junit單元測試方法

最近在做基於SSM框架的開發,使用SpringBoot代替了SpringMVC,怎麼使用Junit單元測試呢? 首先在該服務的pom檔案中新增支援junit的依賴: 然後在src/test/java 目錄下新增一個父類,用來setup WebApplicationCo

SpringBootHttp請求統一異常(返回資料)處理與單元測試

對返回資料格式的統一 首先規定一下錯誤的輸出格式: { "code": 1, "msg": "提示", "data": null } data是一個物件 首先定義一個http請求返回的類 package cn.

(27)Spring Boot Junit單元測試從零開始學Spring Boot

Junit這種老技術,現在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在專案中的重要性。 那麼先簡單說一下為什麼要寫測試用例 1. 可以避免測試點的遺漏,為了更好的進行測試,可以提高測試效率 2. 可以自動測試,可以在專案打包前進行測試校驗 3. 可以及時發現因為

SpringBoot整合JPA啟動基於JPA的單元測試方法報如下錯誤:could not initialize proxy

出現該錯誤,分析了一下原因:基於JPA的實現來說,在進行資料庫訪問的時候,針對資料庫的訪問與操作session已經關閉釋放了。 百度了一下,網上有如下解決方案: 第一種方案:在@OneToMany的引數中使用fetch=FetchType=Eager 未涉及到該註解的使

Java JUnit 單元測試小結

ase module 處理 out () 追蹤 角度 urn 種類 原文鏈接:https://segmentfault.com/a/1190000006731125 測試類型 單元測試(Unit test) 單元測試關註單一的類. 它們存在的目的是檢查這個類中的

Flask Rest API 單元測試

ati rdo ces tps ont basic nal src mon Flask簡單的Rest API 接口測試示例代碼: import unittest import json from app import app class BasicTestCase(un

SpringBoot入門十,新增junit單元測試

SpringBoot使用junit非常簡單,我們來看一下,首先說明,這裡使用的是springboot2.0.4的版本 一.pom.xml檔案開啟springboot測試包 <dependency> <groupId>org.springframework.boot

SpringBoot專案,使用MockMvc做controller類的JUNIT單元測試

package hello; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.t