为什么我的单元测试在我看来“正确”的时候失败了?

2024-06-09 16:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Python。我从单元测试开始:

import unittest

from rna_transcription import to_rna

class RNATranscriptionTests(unittest.TestCase):

    def test_transcribes_cytosine_to_guanine(self):
        self.assertEqual(to_rna('C'), 'G')
if __name__ == '__main__':
    unittest.main()

我这样写我的方法:

def to_rna(dna_strand):
    rna_strand = []

    for x in dna_strand:
        print('looking at:', x)
        if x == 'C':
            rna_strand.append('G')


    return rna_strand

当我运行单元测试时,它失败并出现以下错误:

AssertionError: ['G'] != 'G'

我不确定这里出了什么问题。我没有得到输出。对我来说,G看起来像G,而不是写得不同。我做错了什么?你知道吗


Tags: tofromimportselfifmaindef单元测试
1条回答
网友
1楼 · 发布于 2024-06-09 16:37:35

['G']'G'不同。前者是list,后者是str。列表永远不能等于字符串。你知道吗

但是你的测试是正确的,因为它指出你函数的行为不是预期的。如果你想让它返回一个字符串,你需要它看起来像这样。你知道吗

def to_rna(dna_strand):
    rna_strand = ''

    for x in dna_strand:
        print('looking at:', x)
        # if I recall my biology class correctly 
        rna_strand += 'G' if x == 'C' else x

    return rna_strand

请注意,有更有效的方法可以做到这一点,但我没有更新您的代码太多的例子的缘故。你真的可以这么做。你知道吗

def to_rna(dna_strand):
    return dna_strand.replace('C', 'G')

相关问题 更多 >