Monday, November 26, 2018

java - Mockito and string objects



I've started playing around with mockito today and I've encountered a problem. This is the class I'm trying to create test cases on:



@Path("search")
public class SearchWebService {

private static final Logger logger = Logger.getLogger(SearchWebService.class);

@EJB

UserServiceInterface userService;

@GET
@Path("/json/{searchstring}")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@RolesAllowed("User")
public List getJSONFromSearchResults(@PathParam("searchstring") String searchString, @Context HttpServletRequest request) {
logger.info("getJSONFromSearchResults called");

//Users own email

String ownemail = request.getRemoteUser();

if (searchString.contains(" ")) {
//Split String in two at first space
String names[] = searchString.split("\\s+", 2);

List userList = userService.searchByFullName(names[0], names[1], ownemail);
if (userList.size() > 0) {
return userList;
} //Check for cases where the last name contains spaces

else {
return userService.searchByLastName(searchString, ownemail);
}
}
return userService.searchBySingleName(searchString, ownemail);
}
}


I'm at searchString.contains(" ") and I'm trying to invoke "when(...).thenReturn(...)" But mockito throws an exception saying that "Cannot mock/spy class java.lang.String" I'm not sure I'm doing it correctly when testing this web service. Maybe there is some otherway to do this? Here is my test class:




public class SearchWebServiceTest {

@Mock
UserServiceInterface mockedUserService;
@Mock
Logger mockedLogger;
@Mock
HttpServletRequest mockedRequest;
@Mock

String mockedString;
@Mock
List mockedUserList;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}

@Test

public void testGetJSONFromSearchResultsSpace() throws Exception {
when(mockedRequest.getRemoteUser()).thenReturn("email");
when("StringWithSpace".contains(" ")).thenReturn(true);
when("StringWitchSpace".split("\\s+", 2)).thenReturn(null);
when(mockedUserService.searchByFullName("name1", "name2", "email")).thenReturn(mockedUserList);
assertTrue(mockedUserList.size() > 0);
}

Answer



you cannot mock final classes (like String). This is a known limitation of the framework.




You can refer this link.



Mockito Verification Not Failing



I hope it helps !!!


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...