Java 使用mockito for Rest API的JUnit测试用例

Java 使用mockito for Rest API的JUnit测试用例,java,rest,junit,mockito,Java,Rest,Junit,Mockito,我是Mockito框架的新手,我有一个rest APi,可以将我的应用程序连接到jasper服务器并执行与报表相关的操作。我想使用Mockito框架为rest APi编写junit测试用例 这里我有一个名为Repositoryclient的类,它的构造函数有一个JasperServerInfo DAO类的实例 public class RepositoryClient { public RepositoryClient(ServerInfo serverInfo) {

我是Mockito框架的新手,我有一个rest APi,可以将我的应用程序连接到jasper服务器并执行与报表相关的操作。我想使用Mockito框架为rest APi编写junit测试用例

这里我有一个名为Repositoryclient的类,它的构造函数有一个JasperServerInfo DAO类的实例

public class RepositoryClient {

    public RepositoryClient(ServerInfo serverInfo) {
        this.info = serverInfo;

        try {

            Session = Client.authenticate(info.username.trim(), info.password.trim());
        }
        catch (Exception e) {

        }
    }
     public void Templates() {  //this method brings list of present report in jasper server repository     
        try {
            OperationResult<...> result = ....;               


        } catch (Exception e) {
            INodeProcessor.logger.warn(e.toString());
            throw Error.REPORT_TEMPLATE_LIST_ERROR.with();
        }
}
公共类RepositoryClient{
公共存储客户端(服务器信息服务器信息){
this.info=serverInfo;
试一试{
Session=Client.authenticate(info.username.trim(),info.password.trim());
}
捕获(例外e){
}
}
public void Templates(){//此方法在jasper服务器存储库中提供当前报表的列表
试一试{
操作结果结果=。。。。;
}捕获(例外e){
INodeProcessor.logger.warn(例如toString());
抛出错误。报告\模板\列表\错误。with();
}
}

因此,如何使用mockito为这个类编写JUnit测试用例,请指导我完成。提前谢谢。

好吧,代码可以改进,使其实际可测试

目前,没有真正好的方法为代码编写单元测试,因为构造函数创建了一个JasperserverRestClient,而没有任何机会对其进行更改。您至少可以添加另一个构造函数(可能是包访问)以允许使用另一个JasperserverRestClient。(或者,您可以考虑使用工厂模式,但这可能太复杂了。)

然后你可以嘲笑

JasperserverRestClient jasperServerClient = Mockito.mock( JasperserverRestClient.class );
RestClientSession session = Mockito.mock( RestClientSession.class );

Mockito.when( jasperServerClient.authenticate( "x", "y")).thenReturn( session );

RepositoryClient repositoryClient = new RepositoryClient(jasperServerClient);
这至少允许您通过
Mockito.verify
测试是否使用正确的参数调用了authenticate

它还允许您测试
listTemplates
方法是否使用正确的参数调用会话(当然,您需要在那里进行更多的模拟)

假设您的测试在同一个包中,另一个构造函数将如下所示:

RepositoryClient(JasperserverRestClient httpRestClient, JasperServerInfo serverInfo) {
    this.info = serverInfo;
    this.httpRestClient = httpRestClient;

    try {
        restClientSession = httpRestClient.authenticate(info.username.trim(), info.password.trim());
    }
    catch (Exception e) {
        INodeProcessor.logger.warn(e.toString());
        throw Error.REPOSITORY_CLIENT_ERROR.with();
    }
}
通过这种方式,您可以将JasperserverRestClient的模拟实例注入到对象中

对listTemplates方法的测试(另外)如下所示

X resourcesService = Mockito.mock( X.class ); // No clue what the resourcesService() method is supposed to return, fill that in here
Mockito.when ( restClientSession.resourcesService() ).thenReturn ( resourcesService );
…这将允许部件
restClientSession.resourcesService()
工作。下一步

Y resources = Mockito.mock( Y.class ); // Same thing here, don't know what resources() should return, insert that class here
Mockito.when( resourcesService.resources()).thenReturn ( resources );
这将允许
resources()
调用工作

接下来我们做一些诡计:

Mockito.when(resources.parameter(Mockito.anyString(),Mockito.anyString()).thenReturn(resources);//假设ResourceSearchParameter常量是字符串

这将允许parameter()调用通过返回相同的resources()对象来工作

以此类推……您将需要在(…)时返回(…)搜索方法以返回
操作结果
,等等。但这与上面的内容相同

最后,我们可以验证使用正确的参数调用了这些方法

Mockito.verify( resources, Mockito.times(1)).parameter(ResourceSearchParameter.FOLDER_URI, info.reportDirectory);

Mockito.verify( resources, Mockito.times(1)).parameter(ResourceSearchParameter.RECURSIVE, "false"

Mockito.verify( resources, Mockito.times(1)).search();
将打印:“是的!!!”

@RunWith(SpringJUnit4ClassRunner.class)
公共类UserControllerTest{
@注射模拟
专用用户控制器用户控制器;
@嘲弄
私有属性属性属性属性;
@嘲弄
私人用户服务;
私有MockMvc-MockMvc;
@以前
公共作废设置(){
setRequestAttributes(attrubutes);
this.mockMvc=MockMvcBuilders.standaloneSetup(userController.build();
}
@试验
public void getUserinfoDetails(){
字符串userId=“123”;
字符串userName=“Test145”;
List userDtoList=new ArrayList();
Mockito.when(userService.getAllUserInfo()).thenReturn(userDtoList);
Assert.assertNotNull(userController.getUserinfo());
Assert.assertNotNull(userDtoList);
Assert.assertNotNull(userId);
Assert.assertNotNull(用户名);
}
@试验
public void getUserByIdDetails(){
字符串userId=“123”;
UserDto UserDto=新UserDto();
Mockito.when(userService.getUserByUserId(userId)).thenReturn(userDto);
Assert.assertNotNull(userController.getUserById(userId));
Assert.assertNotNull(userDto);
Assert.assertNotNull(userId);
}
}
===========================================================================

以下链接供参考使用:(逐步解释)


感谢Florian的宝贵反馈。您能帮助我创建构造函数和模拟列表模板吗?这将非常有帮助。我被困在这里非常严重。谢谢Florian。这确实是一个很大的帮助。OperationResult包含作为ClientResourceListWrapper{resourceLookups的响应=[ClientResourceLookup{version=2,permissionMask=1,creationDate='2015-09-20T23:03:32',updateDate='2015-09-20T23:15:24',label='ReportSample',description=''''s,uri='/reports/ReportSample',resourceType='reportUnit'}格式用于每个报表。在(result.readEntity)时返回的预期值是什么(ClientResourceListWrapper.class)。然后返回(??)语句。老实说,我不知道,因为您的评论是第一次提到,
readEntity
;-)您可以为任何对象(除了最终对象)创建模拟,然后在(…)时使用
。然后(…)
construct告诉这个mock它应该返回什么,例如对于getter方法,从而创建一个行为与您想要的一样的对象。另一种方法是手动创建一个ClientResourceListWrapper,为测试填充您想要的值,然后简单地返回。是的,我在上一个问题中有点困惑(无论如何,我根据您的答案找到了解决方案。:)帮助很大。非常感谢。感谢您的回复和有用的链接:)
        getting started example that i have :
        import static org.mockito.Mockito.mock;
        import static org.mockito.Mockito.when;

        @Test(priority = 31, groups = "success")
            public void mockExample() {
                Category category1 = mock(Category.class);
                when(category1.getName()).thenReturn("Yess!!!");
                System.out.println(category1.getName());
            }
you can read from here :

http://examples.javacodegeeks.com/core-java/mockito/mockito-hello-world-example/
@RunWith(SpringJUnit4ClassRunner.class)
public class UserControllerTest {

    @InjectMocks
    private UserController userController;

    @Mock
    private RequestAttributes attrubutes;

    @Mock
    private UserService userService;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        RequestContextHolder.setRequestAttributes(attrubutes);
        this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    }

    @Test
    public void getUserinfoDetails() {
        String userId = "123";
        String userName = "Test145";
        List<UserDto> userDtoList = new ArrayList<>();
        Mockito.when(userService.getAllUserInfo()).thenReturn(userDtoList);
        Assert.assertNotNull(userController.getUserinfo());
        Assert.assertNotNull(userDtoList);
        Assert.assertNotNull(userId);
        Assert.assertNotNull(userName);

    }
    @Test
    public void getUserByIdDetails() {
        String userId = "123";
        UserDto userDto = new UserDto();
        Mockito.when(userService.getUserByUserId(userId)).thenReturn(userDto);
        Assert.assertNotNull(userController.getUserById(userId));
        Assert.assertNotNull(userDto);
        Assert.assertNotNull(userId);
    }
}