如何对从包中导入的方法进行存根和间谍活动?

我是一名 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 total

Tests:       1 passed, 1 total

Snapshots:   0 total

Time:        12.467s

示例中的测试方法在使用Arrange、Act、Assert模式的 js 项目中非常常见。由于该dotenv.config()方法会做一些文件系统 I/O 操作,所以它有一个副作用。所以我们将为它制作一个存根或模拟。这样,我们的单元测试就没有副作用,并且在隔离的环境中进行测试。


这同样适用于 python。我们可以使用unittest.mock模拟对象库来做同样的事情。我对这些单元测试方法非常满意。


桃花长相依
浏览 123回答 1
1回答

三国纷争

这是我基于此答案的解决方案:osEnvFetcher.go:package utilimport (&nbsp; &nbsp; "log"&nbsp; &nbsp; "os"&nbsp; &nbsp; "github.com/joho/godotenv")var godotenvLoad = godotenv.Loadvar logFatal = log.Fataltype EnvFetcher interface {&nbsp; &nbsp; Getenv(key string) string}type osEnvFetcher struct {}func NewOsEnvFetcher() *osEnvFetcher {&nbsp; &nbsp; err := godotenvLoad()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; logFatal("Error loading .env file")&nbsp; &nbsp; }&nbsp; &nbsp; return &osEnvFetcher{}}func (f *osEnvFetcher) Getenv(key string) string {&nbsp; &nbsp; return os.Getenv(key)}osEnvFetcher_test.go:package utilimport (&nbsp; &nbsp; "testing"&nbsp; &nbsp; "errors")func mockRestore(oGodotenvLoad func(...string) error, oLogFatal func(v ...interface{})) {&nbsp; &nbsp; godotenvLoad = oGodotenvLoad&nbsp; &nbsp; logFatal = oLogFatal}func TestOsEnvFetcher(t *testing.T) {&nbsp; &nbsp; // Arrange&nbsp; &nbsp; oGodotenvLoad := godotenvLoad&nbsp; &nbsp; oLogFatal := logFatal&nbsp; &nbsp; defer mockRestore(oGodotenvLoad, oLogFatal)&nbsp; &nbsp; var godotenvLoadCalled = false&nbsp; &nbsp; godotenvLoad = func(...string) error {&nbsp; &nbsp; &nbsp; &nbsp; godotenvLoadCalled = true&nbsp; &nbsp; &nbsp; &nbsp; return errors.New("parsed failure")&nbsp; &nbsp; }&nbsp; &nbsp; var logFatalCalled = false&nbsp; &nbsp; var logFatalCalledWith interface{}&nbsp; &nbsp; logFatal = func(v ...interface{}) {&nbsp; &nbsp; &nbsp; &nbsp; logFatalCalled = true&nbsp; &nbsp; &nbsp; &nbsp; logFatalCalledWith = v[0]&nbsp; &nbsp; }&nbsp; &nbsp; // Act&nbsp; &nbsp; NewOsEnvFetcher()&nbsp; &nbsp; // Assert&nbsp; &nbsp; if !godotenvLoadCalled {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("godotenv.Load should be called")&nbsp; &nbsp; }&nbsp; &nbsp; if !logFatalCalled {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("log.Fatal should be called")&nbsp; &nbsp; }&nbsp; &nbsp; if logFatalCalledWith != "Error loading .env file" {&nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("log.Fatal should be called with: %s", logFatalCalledWith)&nbsp; &nbsp; }}覆盖测试的结果:☁&nbsp; util [master] ⚡&nbsp; go test -v -coverprofile cover.out=== RUN&nbsp; &nbsp;TestOsEnvFetcher--- PASS: TestOsEnvFetcher (0.00s)PASScoverage: 80.0% of statements报道html记者:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go