Reputation: 81
What I'm trying to accomplish is to mock a the split inside a method like this
def method_separator(s):
try:
a, b, c = s.split('-')
print a, b, c
except: ValueError:
print "An error occurred or so"
In the test
with self.assertRaises(ValueError):
with mock.patch(What to put here?) as mock_patch:
mock_patch.return_value = "TEXT" # To raise ValueError
this = method_separator('Some-good-text') # The mock should not let this good test to pass
I've made the mock working with string.split
def method_separator(s):
try:
a, b, c = split.string(s, '-')
print a, b, c
except: ValueError:
print "An error occurred or so"
with self.assertRaises(ValueError):
with mock.patch('string.split') as mock_patch:
mock_patch.return_value = "TEXT" # To raise ValueError
this = method_separator('Some-good-text') # The mock should not let this good test to pass
Even if that work, the question remains, it is posible to do? mock the result of "".split('-')
Upvotes: 1
Views: 6465
Reputation: 710
The string you want to split is passed into your method. You don't need to use patch
, just pass a Mock into the method.
# Production Code
def method_separator(s):
try:
a, b, c = s.split('-')
print a, b, c
except: ValueError:
print "An error occurred or so"
# Test Code
from unittest.mock import Mock
with self.assertRaises(ValueError):
mock_string = Mock(spec=string)
mock_string.side_effect = ValueError("Some message")
this = method_separator(mock_string)
patch
is useful when you want your production to get a mock through an import statement. If you pass values directly to your production code, you have to make your own Mock objects.
Upvotes: 1