小技巧集錦01

1.Edit configurations

在Idean的Edit configurations中編輯應用,

**

** ①,配置VM options的參數時要以:-DparamName的格式設置參數。
springboot Application 中-Dserver…port=8083
②,配置程序參數,program arguments,使用 --paramName 的格式,也能設置程序參數。

在這裏插入圖片描述

2update run****策略

**

  • none 不做改變
  • update resources 更新配置資源
  • update resources and classes 更新配置資源和class字節碼文件

在這裏插入圖片描述

**

3.pom 導入jar失敗時

**

Intellj 的自動載入maven功能有時候很好用,但是有時候會碰到很多問題,導致pom文件修改卻沒有觸發自動重寫載入。
此時需要手動強制更新依賴:

  1. 手動刪除Project Setting 裏面的libraries 包

  2. 在Maven Project點擊clean功能,刪除之前編譯過得文件

在這裏插入圖片描述

  1. 項目右鍵 --》 maven --》 Reimport
    在這裏插入圖片描述
    **

4 - [ ] application.yml 配置失效 ,maven 配置失效,掃描不到配置

**

那些什麼配置文件掃描不到,還有那些配置失效

首先,確認你的編譯過後的target裏面的配置是在裏面的,如果沒有編譯過去,還讀取個雞兒。

怎麼配置?

編譯確保這些文件被編譯過去了。如果是maven項目,標籤下下就是配置這個的,現在我貼上我的配置,以後出現配置失效,記得看target目錄下有有沒有這個配置文件

  • 5

  • SpringBoot怎麼寫單元測試
    SpringBoot提供註解的方式編寫單元測試,可以使用SpringBootTest註解來標示測試類。

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Test
    public void method(){
    }

這樣寫只能解決沒有一些配置文件的測試邏輯,比如沒有數據庫配置、數據庫連接池配置等。如果有這些配置,你就需要這樣寫了。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Test
public void method(){
}

這樣就可以正常運行了。
測試controller類。使用了Mock,網上大多流傳的是下面這種方法,添加@WebAppConfiguration,使用MockMvc去進行單元測試,但是我的項目如下使用就出現了問題,執行的時候找不到Controller類,網上百度了各種方法都不管用。都會報 no bean of ‘controller’ type found錯誤。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
 public class ControllerTest {
 
    private MockMvc mockMvc;
 
    @Autowired
    private WebApplicationContext wac;
 
    @Before // 在測試開始前初始化工作
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }
 
    @Test
    public void getMessageTest() throws Exception {
 
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/getMessage"))
                .andDo(MockMvcResultHandlers.print()).andReturn();
 
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
 
        Assert.assertTrue("success", status == 200);
        Assert.assertFalse("failed", status != 200);
 
        System.out.println("content" + content);
 
 
    }

後來換了一種方式寫,直接new個controller。測試運行,不報no bean of ‘controller’ type found錯誤了。但是在controller中使用的service報了空指針異常NPE,傳遞性就很明顯了,controller是new的一個對象,所以註解不起作用,service就爲null。
最後通過使用@AutoConfigureMockMvc+@MockBean的方式可以實現簡單的單元測試,並且不會對數據產生影響,且不會對數據庫產生影響。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
public class ImkfMessageReportControllerTest {
    /**
     * 初始化MockMvc
     */
    @Autowired
    private MockMvc mvc;
 
    /**
     * 測試的controller
     */
    @MockBean
    private UserController userController;
 
    @Test
    public void getUserListTest() throws Exception {
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get("/user/getUserList"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        System.out.println("content" + content);
 
    }

SpringBoot使用Mockito進行單元測試
上面是使用MockMvc,雖然能夠驗證短鏈接甚至service代碼邏輯的正確性,能夠正常測試接口的問題。但是缺點也不少,比如,覆蓋率並沒有提升。Mockito是一個非常好用的單元測試工具,它的實現原理是繼承要Mock的類,將所有的公有方法進行重寫。

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
 
    @Mock
    private UserMapper userMapper;
 
    @InjectMocks
    private UserService userService;
 
    @Test
    public void save() throws Exception {
        User user = new User();
        user.setUserName(Long.valueOf("springBoot"));
        when(userMapper.insert(user)).thenReturn(user);
        User num = userService.save(user);
        Assert.assertEquals("success", "springBoot", num.getUserName);
  
    }
 
}

使用RunwWith(MockitoJUnitRunner.class)來進行mocktio測試,註解@Mock標記一個類或者接口是需要被mock的。@InjectMocks將所有的mock對象都放入需要測試的類的對象中。使用時,方法裏面調用到UserMapper.insert(),那麼需要對UserMapper.insert()進行打樁,設置預期返回值。
打樁時,傳遞的參數(如果有)必須爲調用時的同一個對象或者相同值,如果傳入的參數是一個對象,那麼需要對這個對象進行打樁,再調用打樁的方法。比如,when(userMapper.insert(user)).thenReturn(rUser),插入一個user對象,如果user插入之前要進行校驗或者其他操作,需要對這個對象進行打樁,rUser同理。如果插入的對象非常複雜,用構造方法來構造一個空對象,或者構造方法所用的對象不能直接構造,但是沒有public的方法來設置值,怎麼辦?

我們知道一個對象的類一定有get方法,我們可以通過Mock來僞裝一個對象,在將要測試的方法體內,如果某行調用了這個對象的任意方法(toString()、equals()、get()),我們都可以以相同的參數進行打樁後設置返回值,這樣就能通過參數校驗等環節,執行後面的代碼邏輯,同時能夠提高覆蓋率。

 @Mock
    private User user; 
 
     when(user.get(eq("userName"))).thenReturn("123456");
     when(user.get(eq("seq"))).thenReturn(4);
     when(user.get(eq("password"))).thenReturn("132242312");
     when(user.get(eq("u_id"))).thenReturn("654321");

==================================
SpringBoot:SpringBoot項目進行單元測試
JUnit是一個迴歸測試框架,被開發者用於實施對應用程序的單元測試,加快程序編制速度,同時提高編碼的質量。

JUnit中常用的的註解如下:
@BeforeClass:針對所有測試,只執行一次,且必須爲static void。
@Before:初始化方法,執行當前測試類的每個測試方法前執行。
@Test:測試方法,在這裏可以測試期望異常和超時時間。
@Test(timeout = 1000) 測試方法執行超過1000毫秒後算超時,測試將失敗。
@Test(expected = Exception.class) 測試方法期望得到的異常類,如果方法執行沒有拋出指定的異常,則測試失敗。
@After:釋放資源,執行當前測試類的每個測試方法後執行。
@AfterClass:針對所有測試,只執行一次,且必須爲static void。
@Ignore:忽略的測試方法(只在測試類的時候生效,單獨執行該測試方法無效)。
@RunWith:可以更改測試運行器 ,缺省值 org.junit.runner.Runner

一個單元測試類執行順序爲:
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一個測試方法的調用順序爲:
@Before –> @Test –> @After

Spring Boot進行單元測試,主要分爲不依賴web模塊的單元測試(Service)和依賴web模塊的單元測試(Controller)兩種。測試步驟如下:

1、在pom中添加Jar包依賴

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

2、不依賴web模塊的單元測試(Service)

import com.example.bean.Student; 

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;
import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class StudentServiceTest {
    @Autowired
    private StudentService studentService;

    @Test
    public void findOne() throws Exception {
    	//測試Id爲1的學生年齡是否爲20
        Student student = studentService.findOne(1);
        Assert.assertEquals(new Integer(20), student.getAge());
    }
}

3、依賴web模塊的單元測試(Controller)
get請求訪問Testcontroller,路徑+"/hello"返回hello字符串。驗證接口是否正常以及返回預期結果判定如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class SpringbootDemoApplicationTests {   
   @Autowired
   private WebApplicationContext webApplicationContext;

   private MockMvc mockMvc;   
   
   @Test
   public  void hello() throws Exception {
      String url = "/hello";//訪問url
      String expectedResult = "hello";//預期返回結果
      
	 mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

      MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON)).andReturn();      
      
      //訪問返回狀態
      int status = mvcResult.getResponse().getStatus();
      System.out.println(status);
      
      //接口返回結果
      String content = mvcResult.getResponse().getContentAsString();
      System.out.println(content);
      //打印結果和狀態

      //斷言狀態
      Assert.assertTrue("成功", status == 200);
      Assert.assertFalse("失敗", status != 200);
      
      //斷言結果
      Assert.assertTrue("數據一致", expectedResult.equals(content));
      Assert.assertFalse("數據不一致", !expectedResult.equals(content));

解釋:
A. @SpringBootTest註解是普通的 Spring 項目(非 Spring Boot 項目)中編寫集成測試代碼所使用的@ContextConfiguration註解的替代品。其作用是用於確定如何裝載 Spring 應用程序的上下文資源。
當運行 Spring Boot 應用程序測試時,@SpringBootTest註解會自動的從當前測試類所在的包起一層一層向上搜索,直到找到一個@SpringBootApplication或@SpringBootConfiguration註釋類爲止。以此來確定如何裝載 Spring 應用程序的上下文資源。
B. 基於 Spring 環境的 Junit 集成測試還需要使@RunWith(SpringJUnit4ClassRunner.class)註解,該註解能夠改變 Junit 並讓其運行在 Spring 的測試環境,以得到 Spring 測試環境的上下文支持。否則,在 Junit 測試中,Bean 的自動裝配等註解將不起作用。但由於 SpringJUnit4ClassRunner 不方便記憶,Spring 4.3 起提供了一個等同於 SpringJUnit4ClassRunner 的類 SpringRunner,因此可以簡寫成:@RunWith(SpringRunner.class)。

7判斷字符串是否爲空

****不要用 if(token == null || “”.equals(token.trim())){ trim ()效率很低
****推薦用 工具類 StringUtils.isBlank(token)和isNotBlank(token)
包 org.apache.commons.lang

 if(StringUtils.isBlank(access-token)){**
       // 沒有access-token,登錄校驗失敗,攔截
       //********
 }

//@return true if the String is null, empty or whitespace

 public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章