我正在尝试用自定义模拟修补函数调用
subscriberMock = MagicMock(side_effect=subscriber)
subscriberMock.return_value.unregister.return_value = True
with patch('rospy.Subscriber', subscriberMock):
data['op'] = "unsubscribe"
data['topic'] = "/helo"
self.rosbridge.incoming(data)
内部方法具有此代码
self.subscribers[topic] = rospy.Subscriber(topic, 'msg', outgoing_function)
self.subscribers[topic].unregister() # <-- AttributeError
但是,当我运行此操作时,它会返回属性错误
'nontype'对象没有属性'unregister'
我猜想return_value
设置为非类型,但我认为此subscriberMock.return_value.unregister.return_value
会覆盖它
更多信息:
如果我打印self.subscribers[topic]
,则返回None
。然后它运行侧面效果。为什么self.subscribers[topic] = None
应该给出我的参数返回值。
而不是上述模拟,您必须在侧面效果中写一个模拟呼叫的实例
def subscriber (topic, topic_type, outgoing_function):
# convert to a ROS object
output = ROSBridgeObject()
output.foo = topic
# pretend we got a message from what we subscribed to
outgoing_function(output)
mock = MagicMock()
subscriberMock.unregister.return_value = True
return mock
subscriberMock = MagicMock(side_effect=subscriber)
这是因为MagicMock的返回值或副作用