在类外模拟方法 [英] Mocking a method outside of a class

查看:84
本文介绍了在类外模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为凭证检查模块编写一个单元测试,如下所示.抱歉,我无法复制确切的代码..但是,我尽力简化一下示例. 我想修补methodA,以便它返回False作为返回值,并测试MyClass以查看是否抛出错误. cred_check是文件名,MyClass是类名. methodA在MyClass之外,返回值checkedcredential为True或False.

I need to write a unit test for credential checking module looks something like below. I apologize I cannot copy the exact code.. but I tried my best to simplify as an example. I want to patch methodA so it returns False as a return value and test MyClass to see if it is throwing error. cred_check is the file name and MyClass is the class name. methodA is outside of MyClass and the return value checkedcredential is either True or False.

def methodA(username, password):
    #credential check logic here...
    #checkedcredential = True/False depending on the username+password combination
    return checkedcredential

class MyClass(wsgi.Middleware):
    def methodB(self, req): 
        username = req.retrieve[constants.USER]
        password = req.retrieve[constants.PW]
         if methodA(username,password):
            print("passed")
        else:
            print("Not passed")
            return http_exception...

我目前拥有的单元测试看起来像...

The unit test I currently have looks like...

import unittest
import mock
import cred_check import MyClass

class TestMyClass(unittest.Testcase):
    @mock.patch('cred_check')
    def test_negative_cred(self, mock_A):
        mock_A.return_value = False
        #not sure what to do from this point....

我要在单元测试中编写的部分是返回http_exception 部分.我正在考虑通过修补methodA来返回False来做到这一点.设置返回值后,编写单元测试以使其按预期工作的正确方法是什么?

The part I want to write in my unittest is return http_exception part. I am thinking of doing it by patching methodA to return False. After setting the return value, what would be the proper way of writing the unittest so it works as intended?

推荐答案

在单元测试中,要测试http_exception返回情况需要做的是:

What you need to do in your unittest to test http_exception return case is:

  1. patch cred_check.methodA返回False
  2. 实例化MyClass()对象(也可以使用Mock代替)
  3. 调用MyClass.methodB(),您可以在其中传递MagicMock作为请求,并检查返回值是否为http_exception的实例
  1. patch cred_check.methodA to return False
  2. Instantiate a MyClass() object (you can also use a Mock instead)
  3. Call MyClass.methodB() where you can pass a MagicMock as request and check if the return value is an instance of http_exception

您的考试成为:

@mock.patch('cred_check.methodA', return_value=False, autospec=True)
def test_negative_cred(self, mock_A):
    obj = MyClass()
    #if obj is a Mock object use MyClass.methodB(obj, MagicMock()) instead
    response = obj.methodB(MagicMock()) 
    self.assertIsInstance(response, http_exception)
    #... and anything else you want to test on your response in that case

这篇关于在类外模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆