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

时间:2015-12-15 07:13:03

标签: java rest junit mockito

我是Mockito框架的新手,我有一个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();
        }
}

那么如何使用mockito为这个类编写JUnit测试用例请指导我。提前谢谢。

3 个答案:

答案 0 :(得分:0)

嗯,代码可以改进,使其实际可测试......

目前,没有很好的方法为代码编写单元测试,因为构造函数创建了一个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使用正确的参数调用身份验证。

此外,它还允许您测试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常量是一个字符串

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

等等......你需要在(...)。然后返回(...)搜索方法以返回OperationResult<ClientResourceListWrapper>等等,但这与上面相同。

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

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();

答案 1 :(得分:0)

        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());
            }

将打印:“Yess !!!”

you can read from here :

http://examples.javacodegeeks.com/core-java/mockito/mockito-hello-world-example/

答案 2 :(得分:0)

@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);
    }
}

================================================ ==========================

以下链接供参考:(逐步说明)

https://www.youtube.com/watch?v=yGLOexeJfKA&t=17s