Reputation: 55
I am trying to get started with nosetests and TDD on my own. From what I understand the point of unit testing is to test as much functionality of a function as possible. So what I want to do is add invalid parameters to my function and verify that this can not be done. For example, I am writing a simple add function
def addBowling(x, y):
try:
return x + y
except TypeError:
print('Exception occured: invalid types')
So for this function I want inputs like 'a' to raise an exception. In my nosetests I want to input 'a' like so.
def testAddNumbers():
assert addBowling(3, 4) == 7
assert addBowling(5, 0) == 5
assert addBowling('a', 0) == TypeError
I want to have a couple asserts that will pass and one assert that will fail. When I run this test it tells me that 1 test failed. I am not sure if I am correct in my understanding but I want this test to say it passed because this is correct functionality for my function.
Any guidance on how to get the results that I am looking for?
Upvotes: 1
Views: 31
Reputation: 55
Thanks to a helpful commenter I was able to learn that assert raises is what I was looking for. I refactored my function so now all it does is add and used assert raises in my test, like so.
def addBowling(x, y):
return x + y
def testAddNumbers():
assert addBowling(3, 4) == 7
assert addBowling(5, 0) == 5
assert_raises(TypeError, addBowling, 'a', 2)
Don't forget to import from nose.tools assert_raises!
Upvotes: 1