Issue
Background
I am trying to test this method inside a class with Mockito:
The first case of the method is when a string equals to a constant.
The second case of the method is when a string equals to anything else except the constant.
This is the string version of this question about anything except a certain integer.
public class Class {
private SomeOtherObjectWithAMethod someOtherObjectWithAMethod;
public Class(SomeOtherObjectWithAMethod someOtherObjectWithAMethod){
this.someOtherObjectWithAMethod = someOtherObjectWithAMethod;
}
public void method(){
if(helperObject.obtainAString().equals(HelperObject.A_STRING_CONSTANT)){
someOtherObjectWithAMethod.thisMethod("stringarg");
}
else{
someOtherObjectWithAMethod.thisMethod("differentarg");
}
}
I know in Mockito you can
Change certain return values in mockito (but only the last one will have effect) according to durron597
Enter
null
inside athenReturn()
method as a means of returning nothing.- Use
anyString()
to serve as a dummy string. - Return a boolean value.
Partial Solution
I have already unit tested the first case (str.equals("This string"))
as written below:
private Class instantiatedClass;
@Test
public void testMethod_thisString(){
whenever(helperObject.obtainAString()).thenReturn(HelperObject.A_STRING_CONSTANT);
instantiatedClass.method()
verify(someOtherObjectWithAMethod).thisMethod("stringarg");
}
I am going to write another test case method like it. I have commented out the part I need help with below:
@Test
public void testMethod_notThisString(){
whenever(helperObject.obtainAString()).thenReturn(/* A String that is not HelperObject.A_STRING_CONSTANT */);
instantiatedClass.method()
verify(someOtherObjectWithAMethod).thisMethod("differentarg");
}
Question
How do I test for any string except for a specific value (or values)?
Solution
While I don't know the way to do "any string except certain ones", this solved my issue:
@Test
public void testMethod_notThisString(){
whenever(helperObject.obtainAString()).thenReturn(HelperObject.CONSTANT1, HelperObject.CONSTANT2, HelperObject.CONSTANT3);
instantiatedClass.method()
verify(someOtherObjectWithAMethod).thisMethod("differentarg");
}
This follows the logic of Overriding Stubbing.
Answered By - isakbob
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.