簡體   English   中英

有哪些可能的方法來對該方法進行單元測試?

[英]What are possible ways to unit test this method?

我目前正在學習如何使用 unittest 模塊。 我有一個像掃雷一樣的板子作為 object,形式如下 class:

class Grid:
    ''' class to represent grid sizes. '''
    def __init__(self, width: int, height: int, margin: int, rows: int, columns: int):
        ''' 
        width: int, in pixels
        height: int, in pixels
        margin: int, in pixels
        row: number of squares along y axis
        columns: number of square along x axis
        '''
        self.width = width
        self.height = height
        self.margin = margin
        self.rows = rows
        self.columns = columns
        self.grid = [[0 for _ in range(self.columns)] for _ in range(self.rows)]

    def gridDraw(self):
        '''draws the grid for the game board'''
        for row in range(self.rows):
            for column in range(self.columns):
                color = white.rgb()
                if self.grid[row][column] == 1:
                    color = green.rgb()
                pygame.draw.rect(screen,
                                color,
                                [(self.margin + self.width) * column + self.margin,
                                 (self.margin + self.height) * row + self.margin,
                                 self.width,
                                 self.height])

    def size(self):
        '''returns width, height, margin values '''
        return(self.width, self.height, self.margin, self.rows, self.columns)
    
    def gridVal(self):
        '''returns grid value'''
        return(self.grid)

我的問題是,我怎么能 go 對這個 gridDraw 方法進行單元測試? 它並不真正屬於我通常使用 assertEqual() 函數等測試輸出的方式。 到目前為止,我的測試 class 如下:

class GridTest(unit.TestCase):

    def test_gridDraw(self):

    def test_size(self):

    def test_gridVal(self): 
 

對於test_sizetest_gridVal ,您可以簡單地創建一個 Grid object 並調用size()gridVal() ,然后 assertEqual 如果其返回值符合預期。

這是一個偽代碼:

def test_size(self):
  grid = Grid(...)
  assertEqual(grid.size(), ...)

def test_gridVal(self): 
  grid = Grid(...)
  assertEqual(grid.gridVal(), ...)

對於test_gridDraw ,它稍微困難一些,您需要通過添加假子類或 mocking 來覆蓋 pygame class 。 然后,您會感應到假的或模擬的 object 以查看其rect()方法是否已使用預期的參數調用。

或者,您可以將gridDraw()分解為getRects()並使其調用者調用pygame.draw.rect ,這樣您就可以將代碼與 pygame 調用分開,並使您的代碼易於測試。

這是原始代碼的偽代碼:

# Replace gridDraw with:
def getRects(self):
  rects = []
  for row in range(self.rows):
    for column in range(self.columns):
      ...
      rects.append(...)
  return rects

gridDraw 的調用者將改為這樣做:

for rect in grad.getRects():
  pygame.draw.rect(rect)

最后, getRects的代碼如下所示:

# Instead of test_gridDraw, we do:
def test_getRects(self):
  grid = Grid(...)
  assertEqual(grid.getRects(), ...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM