java Mockito 和字符串对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25915490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:56:40  来源:igfitidea点击:

Mockito and string objects

javajunitmockito

提问by Sam Gholizadeh

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:

我今天开始玩mockito,但遇到了一个问题。这是我试图在其上创建测试用例的类:

@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:

我在 searchString.contains(" ") 并且我试图调用 "when(...).thenReturn(...)" 但是mockito 抛出一个异常,说“不能模拟/监视类java.lang。 String" 我不确定在测试此 Web 服务时是否正确执行此操作。也许有其他方法可以做到这一点?这是我的测试课:

public class SearchWebServiceTest {

@Mock
UserServiceInterface mockedUserService;
@Mock
Logger mockedLogger;
@Mock
HttpServletRequest mockedRequest;
@Mock
String mockedString;
@Mock
List<SearchResultsContainer> 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);
}

回答by DeepInJava

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

您不能模拟最终类(如 String)。这是该框架的一个已知限制。

You can refer this link.

你可以参考这个链接。

Mockito Verification Not Failing

Mockito 验证没有失败

I hope it helps !!!

我希望它有帮助!!!

回答by Kevin Welker

If you need to invoke your service with a String that has a space, then just pass it a string that has a space. And don't mock the class that you are trying to test. You should mock as little as possible in unit tests. Simply provide real input data that meets the particular conditions of your particular test. Only mock collaborators, and only when you need to. If you need a String (either as a parameter or as a return value of a collaborator) that meets certain conditions, then just provide such an example String.

如果您需要使用带有空格的字符串来调用您的服务,那么只需将一个带有空格的字符串传递给它即可。并且不要嘲笑您要测试的课程。您应该在单元测试中尽可能少地模拟。只需提供满足特定测试特定条件的真实输入数据。仅在需要时模拟协作者。如果您需要一个满足特定条件的字符串(作为参数或作为协作者的返回值),那么只需提供这样一个示例字符串。