I am newbie to unit testing. I am using TestNG with MyEclipse to develop unit test cases for my application. While doing it I am facing some problems with EasyMock. Here is my code (Name of the class, method names and return types are changed for security reasons but you will get a clear idea what I am trying to achieve here).
public MyClass
{
// This is a method in my class which calls a collaborator which I
// want to mock in my test case
public SomeObject findSomething(SomeOtherObject param) throws Exception
{
SomeOtherObject param a = myCollaborator.doSomething(param);
// Do something with the object and then return it
return a;
}
}
Now here is my test. Now what I actually want to achieve in my test case is that I want to check that my function (findSomething) properly throws exception in case some exception is thrown. In future some other developer can change the signature (throws Exception isn't really part of method signature) of the method and remove the throws Exception from my method. So how can I make sure that nobody changes it?
@Test(dataProvider="mydataProvider", expectedExceptions=Exception.class)
public void MyTest(SomeOtherObject param) throws Exception {
{
EasyMock.expect(myCollaboratorMock.doSomething(param)).andThrow(new Exception());
EasyMock.replay(myCollaboratorMock);
}
I am getting exception
"java.lang.IllegalArgumentException: last method called on mock cannot throw java.lang.Exception"
What I am doing wrong here? Can someone shed some light on how to write a test case for my particular scenario?
The collaborator's doSomething()
method doesn't declare that it may throw Exception, and you're telling its mock to throw one. It's not possible.
Exception is a checked exception. It can only be thrown if it's declared in the method signature. If the method has no throws
clause, all it can do is throwing runtime exceptions (i.e. RuntimeException
or any descendant class).