基於PowerMokito的單測

2021-08-26 12:43:53 字數 1920 閱讀 6364

1.接入pom

org.mockito

mockito-core

1.10.19

test

org.powermock

powermock-module-junit4

1.6.4

test

org.powermock

powermock-api-mockito

1.6.4

test

org.springframework

spring-test

4.3.4.release

test

2.新建單測類

import org.mockito.mock;

import org.mockito.mockitoannotations;

import org.powermock.api.mockito.powermockito;

import org.powermock.core.classloader.annotations.preparefortest;

import org.powermock.modules.junit4.powermockrunner;

import static org.mockito.matchers.anyint;

import static org.mockito.matchers.anylist;

import static org.mockito.matchers.anystring;

@runwith(powermockrunner.class)

@preparefortest()

public class ***test

3.mock靜態類

powermockito.mockstatic(靜態類.class);

powermockito.when(靜態類.靜態方法(引數)).thenreturn(mock物件);

4.mock方法中有新建物件的操作

powermockito.whennew(新建類.class).witharguments(mock構造方法引數).thenreturn(mock新建類例項);

5.mock對外呼叫方法

powermockito.when(mock對外依賴類例項.依賴方法(自己構造的引數,anystring(), anyint(), anylong(),...)).thenreturn(理想值);

6.預初始化

@before

public void before()

踩到的坑:

1.在when裡面設定帶有引數的方法,且這個引數依賴於待測方法的入參,那麼這兩個引數必須是同乙個物件,才能觸發mock裡面thenreturn()中的物件;

舉例:powermockito.mockstatic(indexfactory.class);

powermockito.when(indexfactory.getestransportclient(getclientnodes())).thenreturn(spyclient);

eseasyclient easyclient = new eseasyclient(getclientnodes());

public eseasyclient(listnodes)

這個時候,拿到的transportclient就是null;

需要新建乙個物件統一入參,才能獲取到mock的spyclient;

listnodes = getclientnodes();

powermockito.when(indexfactory.getestransportclient(nodes)).thenreturn(spyclient);

eseasyclient easyclient = new eseasyclient(nodes);

public eseasyclient(listnodes)

基於C 的單例模式

單例模式是一種設計模式.單例模式表示在定義的某乙個類中,只能有唯一的乙個物件 即只能有乙個例項 優點 提高了封裝性,外部不能輕易的改變例項.含義 程式啟動後就會立即載入到記憶體.缺點 啟動比較慢.如下 include using namespace std template class single...

基於Python OpenCV的單目標輪廓匹配

python opencv 實現單目標餐盤輪廓識別 import cv2 import numpy as np def template template temp cv2.imread template,0 temp gray cv2.cvtcolor temp,cv2.color bgr2gra...

基於C 的單鏈表的實踐

標頭檔案的宣告 pragma once ifndef header h define header h include using namespace std define ok 1 define error 0 define null 0 define overflow 2 typedef int...