【发布时间】:2023-03-15 04:00:01
【问题描述】:
我今天开始玩 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);
}
}
我在 searchString.contains(" ") 并试图调用 "when(...).thenReturn(...)" 但是 mockito 抛出一个异常说 "Cannot mock/spy class 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);
}
【问题讨论】:
-
你想模拟 .contains() 的操作吗?
-
是的,尝试在 when 方法中直接模拟 String 对象和现在的字符串。不工作。我也是测试新手,所以也许已经有一种特定的方法来模拟 String 方法。
-
你到底想测试什么?
-
对我来说,在使用模拟框架的理解上似乎存在问题。您的断言是在一个模拟对象上。模拟是为了模拟不需要的依赖项,并测试一些真实的代码。见:stackoverflow.com/questions/2665812/what-is-mocking
-
请关注@Aritra 和她的cmets。在任何情况下,您都不应该模拟 Java 字符串——永远。只需使用真正的字符串。