测试Python代码

4 投票
1 回答
659 浏览
提问于 2025-04-16 10:59

我想测试一段Python代码,这段代码需要从另一个函数(比如MeasureRadius)获取输入。但是MeasureRadius还没准备好,因为它依赖于我还没收到的一个仪器。那我该怎么测试CalculateArea这个函数,使用不同的iRadius值和MeasureRadius返回的iErrorCode呢?如果能自动化测试就更好了。我本来打算用unittest,但我不知道怎么修改MeasureRadius返回的iRadius和iErrorCode。

class Instrument():
 def MeasureRadius(self):
    iErrorCode = 0
    sErrorMsg = ""
    iRadius = 0
    try:
        #tell the instrument to measure param A, the measurement goes into iRadius param
        #iRadius = Measure()   

    except:
        sErrorMsg = "MeasureRadius caught an exception."
        iErrorCode = 1
    return iRadius, iErrorCode, sErrorMsg

def CalculateArea():

 """calculate area from the measured radius. Returns area, error code, error message"""

  iRadius, iErrorCode, sErrorMsg = Instrument.MeasureRadius()
  if iErrorCode != 0:
      return 0.0,iErrorCode, sErrorMsg
  if iRadius <1 :
      return 0.0,1, "Radius too small."
  fArea = 3.14*iRadius*iRadius
  return fArea,0,""

1 个回答

4

你需要一个“模拟工具”,用来替代Instrument这个类。

同时,你还需要重新设计CalculateArea,让它可以进行测试。

def CalculateArea( someInstrument ):
    iRadius, iErrorCode, sErrorMsg = someInstrument.measureRadius()
    # rest of this is the same.

class MockInstrument( object ):
    def __init__( self,  iRadius, iErrorCode, sErrorMsg ):
        self.iRadius= iRadius
        self.iErrorCode= iErrorCode
        self.sErrorMsg= sErrorMsg
    def measureRadius( self ):
        return self.iRadius, self.iErrorCode, self.sErrorMsg
class TestThisCondition( unittest.TestCase ):
    def setUp( self ):
        x = MockInstrument( some set of values )
    def test_should_do_something( self ):
        area, a, b = CalculateArea( x )
        assert equality for the various values.

撰写回答