亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對從包中導入的方法進行存根和間諜活動?

如何對從包中導入的方法進行存根和間諜活動?

Go
桃花長相依 2022-06-06 15:02:39
我是一名 JavaScript 和 Python 開發人員。這是一個使用jestjs測試框架的單元測試代碼片段:index.ts:import dotenv from 'dotenv';export class OsEnvFetcher {  constructor() {    const output = dotenv.config();    if (output.error) {      console.log('Error loading .env file');      process.exit(1);    }  }}index.test.ts:import { OsEnvFetcher } from './';import dotenv from 'dotenv';describe('OsEnvFetcher', () => {  afterEach(() => {    jest.restoreAllMocks();  });  it('should pass', () => {    const mOutput = { error: new Error('parsed failure') };    jest.spyOn(dotenv, 'config').mockReturnValueOnce(mOutput);    const errorLogSpy = jest.spyOn(console, 'log');    const exitStub = jest.spyOn(process, 'exit').mockImplementation();    new OsEnvFetcher();    expect(dotenv.config).toBeCalledTimes(1);    expect(errorLogSpy).toBeCalledWith('Error loading .env file');    expect(exitStub).toBeCalledWith(1);  });});單元測試的結果: PASS  stackoverflow/todo/index.test.ts (11.08s)  OsEnvFetcher    ? should pass (32ms)  console.log    Error loading .env file      at CustomConsole.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)----------|---------|----------|---------|---------|-------------------File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|-------------------All files |     100 |       50 |     100 |     100 |                    index.ts |     100 |       50 |     100 |     100 | 6                 ----------|---------|----------|---------|---------|-------------------Test Suites: 1 passed, 1 totalTests:       1 passed, 1 totalSnapshots:   0 totalTime:        12.467s示例中的測試方法在使用Arrange、Act、Assert模式的 js 項目中非常常見。由于該dotenv.config()方法會做一些文件系統 I/O 操作,所以它有一個副作用。所以我們將為它制作一個存根或模擬。這樣,我們的單元測試就沒有副作用,并且在隔離的環境中進行測試。這同樣適用于 python。我們可以使用unittest.mock模擬對象庫來做同樣的事情。我對這些單元測試方法非常滿意。
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

這是我基于此答案的解決方案:


osEnvFetcher.go:


package util


import (

    "log"

    "os"

    "github.com/joho/godotenv"

)


var godotenvLoad = godotenv.Load

var logFatal = log.Fatal


type EnvFetcher interface {

    Getenv(key string) string

}


type osEnvFetcher struct {}


func NewOsEnvFetcher() *osEnvFetcher {

    err := godotenvLoad()

    if err != nil {

        logFatal("Error loading .env file")

    }

    return &osEnvFetcher{}

}


func (f *osEnvFetcher) Getenv(key string) string {

    return os.Getenv(key)

}

osEnvFetcher_test.go:


package util


import (

    "testing"

    "errors"

)



func mockRestore(oGodotenvLoad func(...string) error, oLogFatal func(v ...interface{})) {

    godotenvLoad = oGodotenvLoad

    logFatal = oLogFatal

}


func TestOsEnvFetcher(t *testing.T) {

    // Arrange

    oGodotenvLoad := godotenvLoad

    oLogFatal := logFatal

    defer mockRestore(oGodotenvLoad, oLogFatal)

    var godotenvLoadCalled = false

    godotenvLoad = func(...string) error {

        godotenvLoadCalled = true

        return errors.New("parsed failure")

    }

    var logFatalCalled = false

    var logFatalCalledWith interface{}

    logFatal = func(v ...interface{}) {

        logFatalCalled = true

        logFatalCalledWith = v[0]

    }

    // Act

    NewOsEnvFetcher()

    // Assert

    if !godotenvLoadCalled {

        t.Errorf("godotenv.Load should be called")

    }

    if !logFatalCalled {

        t.Errorf("log.Fatal should be called")

    }

    if logFatalCalledWith != "Error loading .env file" {

        t.Errorf("log.Fatal should be called with: %s", logFatalCalledWith)

    }

}

覆蓋測試的結果:


?  util [master] ?  go test -v -coverprofile cover.out

=== RUN   TestOsEnvFetcher

--- PASS: TestOsEnvFetcher (0.00s)

PASS

coverage: 80.0% of statements

報道html記者:

http://img1.sycdn.imooc.com//629da76b0001a2fc10200991.jpg



查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號