title: Mockito and string objects
body: <p>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:</p>
  
  <pre><code>@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() &gt; 0) {
              return userList;
          } //Check for cases where the last name contains spaces
          else {
              return userService.searchByLastName(searchString, ownemail);
          }
      }
      return userService.searchBySingleName(searchString, ownemail);
  }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>public class SearchWebServiceTest {
  
  @Mock
  UserServiceInterface mockedUserService;
  @Mock
  Logger mockedLogger;
  @Mock
  HttpServletRequest mockedRequest;
  @Mock
  String mockedString;
  @Mock
  List&lt;SearchResultsContainer&gt; 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() &gt; 0);
  }
  </code></pre>