Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test an application using Google Drive API (Java client)

What is the best way to unit test an application using the Google Drive API (Java client)?

It seems like applications written rely heavily on the Drive class, but short of either...

  • creating a really extensive mock (which, itself, would likely need to be tested), or
  • writing an integration test dependent on the actual Drive service

...how could such an application be tested?

Using mock frameworks like Mockito are a bit tedious with the Drive API (Java client), since usage of the Drive Java client rely on making so many chained calls (e.g., from the documentation):

Drive service = getDriveService(req, resp);
service.files().get(fileId).execute();
like image 844
Jon Newmuis Avatar asked Nov 18 '12 19:11

Jon Newmuis


People also ask

How do you perform a unit test in Java?

To perform unit testing, we need to create test cases. The unit test case is a code which ensures that the program logic works as expected. The org. junit package contains many interfaces and classes for junit testing such as Assert, Test, Before, After etc.

How do I test Java locally?

If you're running Eclipse, select the source file of the test to run. Select the Run menu > Run As > JUnit Test. The results of the test appear in the Console window. Note: It is good practice to store your unit tests in a different location than your application code.

How do I unit test API?

An API test is similar to a unit test with a setup (prepare data for calling the API method), a call to the API method and then checking of the results. The semantics may require multiple calls to the API, producing tests that have more than one step.


1 Answers

It shouldn't be that tedious in Mockito in fact, with the help of deep stub:

Drive mockDrive = mock(Drive.class, RETURNS_DEEP_STUBS);

....
// stubbing
when(service.files().get(anyString()).execute()).thenReturn(something);

// verify
verify(service.files().get("Some Field ID").execute();

Learn more from documentation of Mockito

It is fine if you write integration test to test against the actual Drive service, but it simply cannot replace unit testing.

like image 64
Adrian Shum Avatar answered Nov 14 '22 08:11

Adrian Shum