With Objectify you can do it like this. For example, let's declare our BooksEndpoint
as follows:
@Api(
name = "books",
version = "v1",
namespace = @ApiNamespace(ownerDomain = "backend.example.com", ownerName = "backend.example.com", packagePath = "")
)
public class BooksEndpoint {
@ApiMethod(name = "saveBook")
public void saveBook(Book book, User user) throws OAuthRequestException, IOException {
if (user == null) {
throw new OAuthRequestException("User is not authorized");
}
Account account = AccountService.create().getAccount(user);
ofy().save()
.entity(BookRecord.fromBook(account, book))
.now();
}
}
To test it, you would need following dependencies:
testCompile 'com.google.appengine:appengine-api-labs:1.9.8'
testCompile 'com.google.appengine:appengine-api-stubs:1.9.8'
testCompile 'com.google.appengine:appengine-testing:1.9.8'
testCompile 'junit:junit:4.12'
Now, test will look as follows:
public class BooksEndpointTest {
private final LocalServiceTestHelper testHelper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig()
);
private Closeable objectifyService;
@Before
public void setUp() throws Exception {
testHelper.setUp();
objectifyService = ObjectifyService.begin(); // required if you want to use Objectify
}
@After
public void tearDown() throws Exception {
testHelper.tearDown();
objectifyService.close();
}
@Test
public void testSaveBook() throws Exception {
// Create Endpoint and execute your method
new BooksEndpoint().saveBook(
Book.create("id", "name", "author"),
new User("example@example.com", "authDomain")
);
// Check what was written into datastore
BookRecord bookRecord = ofy().load().type(BookRecord.class).first().now();
// Assert that it is correct (simplified)
assertEquals("name", bookRecord.getName());
}
}
Note, I'm using BookRecord
and Book
here - those are my Entity and POJO, nothing special.