Please assist in this. I can't seem to create a suitable test for this method:
protected void startInterfacing() {
mLiveAuthClient.login(mView.context(), Arrays.asList(SCOPES), new LiveAuthListener() {
#Override
public void onAuthComplete(final LiveStatus liveStatus, final LiveConnectSession liveConnectSession,
Object o) {
// Login successful and user consented, now retrieve user ID and connect with backend server
getUserIdAndConnectWithBackendServer(liveConnectSession, mLiveAuthClient);
}
#Override
public void onAuthError(LiveAuthException e, Object o) {
// We failed to authenticate with auth service... show error
if (e.getError().equals("access_denied") ||
e.getMessage().equals("The user cancelled the login operation.")) {
// When user cancels in either the login or consent page, we need to log the user out to enable
// the login screen again when trying to connect later on
logUserOut(mLiveAuthClient, false);
} else {
onErrorOccured();
}
}
});
}
I'll explain abit what goes on here:
I'm trying to authenticate my client and log into OneDrive.
The method starts with a call to the Live SDK's login method. That SDK object is given to me from outside this class. So I can basically mock it.
Here's what I'm struggling with:
I do not need to test the call to the login method because it is not mine. I do need to test the call to getUserIdAndConnectWithBackendServer() inside onAuthComplete. But this method requires a liveConnectSession object. How do I provide that? It is given to me on the onAuthComplete method.
How do I mock the calls to onAuthComplete and onAuthError? I read about ArgumentCaptor but when I use that, I need to provide the arguments to those methods when I call the actual method.
For instance, argument.getValue().onAuthComplete() requires me to add arguments to this call. What do I actually provide here?
Here is the next method which is roughly the same but has its own issues:
protected void getUserIdAndConnectWithBackendServer(final LiveConnectSession liveConnectSession, final LiveAuthClient
authClient) {
final LiveConnectClient connectClient = new LiveConnectClient(liveConnectSession);
connectClient.getAsync("me", new LiveOperationListener() {
#Override
public void onComplete(LiveOperation liveOperation) {
// We got a result. Check for errors...
JSONObject result = liveOperation.getResult();
if (result.has(ERROR)) {
JSONObject error = result.optJSONObject(ERROR);
String code = error.optString(CODE);
String message = error.optString(MESSAGE);
onErrorOccured();
} else {
connectWithBackend(result, liveConnectSession, authClient);
}
}
#Override
public void onError(LiveOperationException e, LiveOperation liveOperation) {
// We failed to retrieve user information.... show error
onErrorOccured();
logUserOut(authClient, false);
}
});
}
In here I would like to mock the JSONObject for instance. But how do I call the onComplete method, or the onError method. And what would I provide as the arguments the methods provide me with. LiveOperation for instance?
Thank you!!
The solution I eventually used was to use mockito's doAnswer() structure.
This enabled me to get the callback argument and call one of its methods.
Another solution was to use an ArgumentCator.
Related
I am implementing in-app billing. I am able to do all I want so far until it comes to checking the users previous purchases. In my first activity in onCreate I create an instance of my BillingManger class which handles all of the in-app billing.
I then call a getPurchases to retrieve a PurchaseResult object in the after this in the onCreate (& onResume) methods:
//Creating instance....
billingManager = new BillingManager(this, this.snackCoordinatorLayout);
//Checking purchases....
billingManager.getPurchases(this);
The getPurchases method creates a instance of a class which extends AsyncTask to query the purchases asynchronously. It takes a listener for the call-back and a BillingClient member variable (this is where I think I may be going wrong - explained why at the end.):
//Querying purchases with AsyncTask
void getPurchases(PurchaseAsyncResponse listener) {
CheckPurchasesAsync check = new CheckPurchasesAsync(listener, this.mBillingClient);
check.execute();
}
Here's the AsyncTask class. This returns a PurchaseResult via an interface callback which it successfully does.
public class CheckPurchasesAsync extends AsyncTask<Void, Void, Purchase.PurchasesResult> {
private PurchaseAsyncResponse listener;
private BillingClient mBillingClient;
CheckPurchasesAsync(PurchaseAsyncResponse listener, BillingClient billingClient) {
this.listener = listener;
this.mBillingClient = billingClient;
}
#Override
protected Purchase.PurchasesResult doInBackground(Void... voids) {
return mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
}
#Override
protected void onPostExecute(Purchase.PurchasesResult purchasesResult) {
listener.purchaseAsyncResponse(purchasesResult);
}
Now in the call-back is where I release something isn't working as I wanted.
#Override
public void purchaseAsyncResponse(Purchase.PurchasesResult purchase) {
if (purchase.getPurchasesList() != null) {
getMessage("mPurchaes NotNull");
//Only need to get the first element - element 0 because their is only one product for now.
if (purchase.getPurchasesList().get(0).getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
getMessage("Unlocking everything");
unlockEveryThing();
}
} else {
getMessage("mPurchases Null ASYNC");
}
}
purchase.getPurchasesList() is null when it shouldn't be so I get a snackbar message called in the resulting else statement.
As part of debugging I called queryPurchase in another method. I have a button that allows the user to purchase premium features for the first time (that is suppose to disappear if I didn't have the problem I am asking about.) I have conditions set-up that show a message for different billing response codes. So as it stands now after buying for the first time, any time there after I display a message saying item already owned.
However, I quired the purchases in this block and was able to get back a successful PurchaseResult object and I was then able to use the getPurchaseList method to find out details about the purchase and it wasn't null like it is in the instance I explained about above. Here is that code snippet:
else if (responseCode.getResponseCode() == BillingResponseCode.ITEM_ALREADY_OWNED) {
getMessage("Item already owned");
Purchase.PurchasesResult PR = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
getMessage(String.valueOf(PR.getPurchasesList().get(0).getSku()));
}
Is the problem that I am sending the mBillingClient to the AysncTask class and it loses its reference and all its meaning?
If so, how could I fix this?
So in the end up I needed to use the startConnection method of the BillingClient. After this all worked as desired.
I want to delete the message from history in Pubnub and I am using this code
AppController.pubNub.deleteMessages()
.channels(Arrays.asList(Constants.channelAtLogin+chat_user_id))
.start(result.getMessages().get(i).getTimetoken())
.end(result.getMessages().get(i).getTimetoken())
.async(new PNCallback<PNDeleteMessagesResult>() {
#Override
public void onResponse(PNDeleteMessagesResult result, PNStatus status) {
Log.d("delete_message",result.toString());
}
});
But message is not deleted . Please help.
It seems like you are trying to show the result variable from your call which shouldn't give any result. The proper way to check if you're getting an error is to log the status. In other words, the code you're using above in essence is the correct code and is the one supported by PubNub.
pubnub.deleteMessages()
.channels(Arrays.asList("channel_1", "channel_2"))
.start(1460693607379L)
.end(1460893617271L)
.async(new PNCallback<PNDeleteMessagesResult>() {
#Override
public void onResponse(PNDeleteMessagesResult result, PNStatus status) {
// The deleteMessages() method does not return actionable data, be sure to check the status
// object on the outcome of the operation by checking the status.isError().
Log.d("Message_Deleted", status.isError().toString());
}
});
If it isn't working the next step is to verify the data from the variables you are passing in.
I am attempting to create a real-time communication capability for a Phonegap/Cordova app. I am using SignalR 2 to handle the communication.
The thing I am struggling with is getting a message to a particular user. Every single example out there shows saving Context.User.Identity.Name, which is useless to me because the remote site's User.Identity context is not shared by my phonegap app.
In essence, I am not authenticating a user in the traditional sense, so I need another way of linking the SignalR connectionID with the username I pass along.
Taken from the official ASP.NET signalr Examples, I have the following code which overrides the OnConnected event. Unfortunately it takes no parameters and expects User.Identity to be not null:
public override Task OnConnected()
{
using (var db = new UserContext())
{
// Retrieve user.
var user = db.Users
.Include(u => u.Rooms)
.SingleOrDefault(u => u.UserName == Context.User.Identity.Name);
// If user does not exist in database, must add.
if (user == null)
{
user = new User()
{
UserName = Context.User.Identity.Name
};
db.Users.Add(user);
db.SaveChanges();
}
else
{
// Add to each assigned group.
foreach (var item in user.Rooms)
{
Groups.Add(Context.ConnectionId, item.RoomName);
}
}
}
return base.OnConnected();
}
Now, maybe what I'd need is to have a version of this method that takes a string as a parameter and then I'd use that as my user identifier.
But how to go about that?
You need to create a new IUserIdProvider for the user and use dependency injection to register your provider and use it.
public interface IUserIdProvider
{
string GetUserId(IRequest request);
}
Register your provider with Global Host
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new MyIdProvider());
Usage:
public class MyHub : Hub
{
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}
}
Taken from: http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#IUserIdProvider
Where is the documentation/sample for all overloads of invokeApi function for Azure Mobile Service client SDK for Android?
I found this article and tried following code, which does not work. There are no compile time or run time errors, invokeApi gets called, but it does not come back to onSuccess or onFailure. If I call invokeApi without order object, everything works as expected
PizzaOrder order = new PizzaOrder();
order.Size = "Large";
order.Flavor = "Four cheeses";
order.UserPhone = "555-555-1234";
ListenableFuture<PizzaOrderResponse> testresult = mClient.invokeApi("bookservice", order, PizzaOrderResponse.class);
Futures.addCallback(testresult, new FutureCallback<PizzaOrderResponse>() {
#Override
public void onFailure(Throwable exc) {
// failure handling code here
}
#Override
public void onSuccess(PizzaOrderResponse testresult) {
// success handling code here
}
});
One of the properties in the data object being returned by the custom API had incorrect data type. I am still not sure where the good documentation is and why custom API call did not fail but at least it is working now.
i am attempting to implement a built in controller that is part of the scoreloop library. the documentation states:
Basic Usage:
To invoke the TOS dialog if it was not accepted previously, the following code may be used:
final TermsOfServiceController controller = new TermsOfServiceController(new TermsOfServiceControllerObserver() {
#Override
public void termsOfServiceControllerDidFinish(final TermsOfServiceController controller, final Boolean accepted) {
if(accepted != null) {
// we have conclusive result.
if(accepted) {
// user did accept
}
else {
// user did reject
}
}
}
});
controller.query(activity);
but when i paste this into my code i get the following syntax errors:
am i using this incorrectly? how and where would this be used any ideas?
EDIT: after moving the statement to the method where i want to show the dialog i now get the following error:
You seem to be calling controller.query(activity) in a class body where a declaration is expected. Move the statement controller.query(activity) to a method where you would like to show the dialog.