对于测试覆盖范围,我还想测试文件“ signalC”中该功能的异常块:

 class SignalC:
    def readSignal(self, a):
    try:
        with open(os.path.join(self.newSubFolder, "my file" + '.csv'), 'a') as csvfile:
            writer = csv.writer(csvfile, delimiter=',', quotechar='|',
                                quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
            print 'Reading'
            z = random.uniform(-0.1, 0.1)
            readValue = z + setP[element]

            writer.writerow([self.element + '-' + str(element+1),)
    except IOError as message:
        logging.error('Error in writing the csv file ' + str(message))
        print(message.strerror)
        raise IOError


到目前为止,我尝试了这种方法,但仍然无法进入异常块:

def testReadSignal(self):
    sc = signalC.SignalC()
    a = [1, 1, 1]
    with mock.patch("signalC.SignalC.readSignal", side_effect=IOError("IOError")):
        self.assertRaises(IOError, sc.readSignal, a)


还是我应该用错误的输入引发异常?谁能举任何例子?提前致谢

最佳答案

似乎您要创建SignalC的实例,然后调用该readSignal方法。因此,您不应该修补该方法本身("signalC.SignalC.readSignal"),因为这意味着它将被模拟,并且您将不会调用该方法的真正实现。

您可以在调用IOError时举起open,例如:

def testReadSignal(self):
    sc = signalC.SignalC()
    a = [1, 1, 1]
    with mock.patch("signalC.open", side_effect=IOError("IOError")):
        self.assertRaises(IOError, sc.readSignal, a)

09-25 22:24