I'm trying to mock the following code using PowerMock
Twitter twitter = TwitterFactory.getSingleton();
RequestToken requestToken = twitter.getOAuthRequestToken();
Here is the start of my unit test
#RunWith(PowerMockRunner.class)
#PrepareForTest(TwitterFactory.class)
public class AuthorisationHelperTest {
#Test
public void testMain() throws TwitterException {
// Arrange
PowerMockito.mockStatic(TwitterFactory.class);
Twitter mockTwitter = new Twitter();
Mockito.when(TwitterFactory.getSingleton()).thenReturn(mockTwitter);
However I get an error saying I cannot instantiate the type Twitter. I figure I must be thinking about this the wrong way. Any tips?
Here's how you declare and instantiate a new instance of a Twitter object:
Twitter twitter = TwitterFactory.getSingleton();
If you cannot instantiate a Twitter class, the likelihood is that it has a non-visible constructor, and is only ever possible to get via the factory.
What you probably want to do is supply a mock of Twitter instead.
Twitter twitter = mock(Twitter.class);
Related
I got a rest api which returns me this nested response:
"latitude":37.8267,
"longitude":-122.4233,
"timezone":"America/Los_Angeles",
"minutely":{
"summary":"Clear for the hour.",
"icon":"clear-day",
"data":[
{
"time":1517431560,
"precipIntensity":0,
"precipProbability":0
},
{
"time":1517431620,
"precipIntensity":0,
"precipProbability":0
},
....
So, I need to get minutely weather forecast and put it to the object. I made a HourlyWeather class with getters and setters (not listed):
public class HourlyWeather {
String time;
String precipIntensity;
String precipProbability;
And here are my gherkin steps implemented with java:
#Given("^rest api$")
public void restApi() throws Throwable {
restApiUrl = "https://api.darksky.net/forecast/******"; // my api key
}
#And("^rest api parameters$")
public void restApiParameters() throws Throwable {
restApiUrl = restApiUrl + "/37.8267,-122.4233";
}
#When("^I \"([^\"]*)\" rest api execution result$")
public void iRestApiExecutionResult(String method) throws Throwable {
RestAssured.baseURI = restApiUrl;
RequestSpecification httpRequest = RestAssured.given(); response = httpRequest.request(Method.GET);
}
and here is my question: I'm using rest assured here to get a part of my nested JSON (which I need). And I do a toString conversion here. After that - I'm using GSON to deserialize my string and create a HourlyWeather[] object with all hourly weather json keys data. Is there any way I could avoid this conversion and simplify my code?
#Then("^I should deserialize result just to know how to do that$")
public void iShouldDeserializeResultJustToKnowHowToDoThat() throws Throwable {
// get only part of my nested json
// I would like ot get this part as an array list of HourlyWeather.class objects, not
// as ArrayList of HashMaps, so this is String here
String stringOfRequiredJSON = response.jsonPath().getJsonObject("minutely.data").toString();
Gson gson = new Gson();
HourlyWeather[] hourlyWeatherForecast = gson.fromJson(stringOfRequiredJSON, HourlyWeather[].class);
printHourlyWeather(hourlyWeatherForecast);
}
Thank you!
Yes, if you are willing to switch to another tool, you must evaluate Karate it frees you from having to fight with JSON in Java, which let us all admit - is not the best language to work with JSON.
I'd also like to point to my detailed answer on why trying to use BDD for REST API testing is not the best use of your time: https://stackoverflow.com/a/47799207/143475
I'm trying to figure out how to integrate an external API and run every integration test against it. I've been reading and looking at:
https://github.com/dropwizard/dropwizard/blob/master/dropwizard-example/src/test/java/com/example/helloworld/IntegrationTest.java
https://github.com/dropwizard/dropwizard/blob/master/docs/source/manual/testing.rst
but it looks like these are examples of testing local endpoints and not external ones. I would like to be able to test my api calls with JUnit tests. Currently I'm having to start up and run my app to make sure they're working.
This is the direction I'm currently exploring:
private Client client;
#Before
public void setUp() throws Exception {
client = ClientBuilder.newClient();
}
#After
public void tearDown() throws Exception {
client.close();
}
#Test
public void testHitApi() throws Exception {
client.target("https://api.github.com/users/" + getUser() + "/repos");
}
Any help would be much appreciated, thanks!
You need to make the api call to hit the endpoint.
doing just :
client.target("https://api.github.com/users/" + getUser() + "/repos")
returns a WebTarget .
you should ideally do something like:
client
.target("https://api.github.com/users/" + getUser() + "/repos")
.request()
.get() ; // for a get call
google for exact post/put/delete calls .
If you mean to run your integration tests against an external api or a separate running instance of your api.
testEnvironment = new Environment("Test environment", Jackson.newObjectMapper(),
null, new MetricRegistry(), null);
ObjectMapper mapper = Jackson.newObjectMapper(new YAMLFactory());
IntegrationTestConfiguration integrationTestConfiguration = mapper.readValue(fixture("integration-testing-config.yml"),
IntegrationTestConfiguration.class);
Instantiate your client as so
exampleClient = new exampleClient(testEnvironment, clientConfiguration);
Hope this helps.
I've got a problem with trying to authenticate to Twitter using twitter4j. I've tried this out and yet it is still not working.
Here's my code, any help would be greatly appreciated.
Thanks.
public class SpeedDemon {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws TwitterException {
// Setup for Snake Charmer
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("CONSUMER_KEY")
.setOAuthConsumerSecret("CONSUMER_SECRET")
.setOAuthAccessToken("OAUTH_ACCESS")
.setOAuthAccessTokenSecret("OAUTH_SECRET");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
// Gets timeline.
Twitter twit = TwitterFactory.getSingleton();
List<Status> statuses = twit.getHomeTimeline();
System.out.println("Showing home timeline.");
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}
}
}
EDIT: The following error happens at compilation:
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:215)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1784)
at twitter4j.TwitterImpl.getHomeTimeline(TwitterImpl.java:105)
at speeddemon.SpeedDemon.main(SpeedDemon.java:30)
C:\Users\Kevin\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
It looks like you construct a Twitter instance twice, once with your constructed TwitterFactory and once with the Singleton (which I suspect doesn't have auth setup).
You then use the second Twitter instance (created with the unauthenticated factory) to make your queries.
Try using twitter.getHomeTimeline() rather than twit.getHomeTimeline()
I have a function that processes events obtained by a PullSubscription to Microsoft Exchange.
public void processEvents(ExchangeService service, PullSubscription subscription)
throws Exception {
GetEventsResults events = subscription.getEvents();
// Loop through all item-related events.
for (ItemEvent itemEvent : events.getItemEvents()) {
if (itemEvent.getEventType() == EventType.NewMail) {
EmailMessage message = EmailMessage.bind(service, itemEvent.getItemId());
EmailParser emailParser = new EmailParser();
emailParser.parse(message, service);
}
}
}
I am trying to test it using PowerMockito because ExchangeService is a final class.
So I have mocked ExchangeService and PullSubscription as follows:
ExchangeService serviceMock = PowerMockito.mock(ExchangeService.class);
PullSubscription subscriptionMock = PowerMockito.mock(PullSubscription.class);
#Test
public void startPullNotification() throws Exception {
ProcessEmails pr = new ProcessEmails("config.properties");
pr.startPullNotification(serviceMock);
}
When I'm trying to test it using the following code it throws a NullPointerException because subscription.getEvents() returns null (i.e. the subscriptionMock has no events in it).
I tried stubbing it by mocking the eventResults that has to be returned:
when(subscriptionMock.getEvents()).thenReturn(eventResultsMock);
It doesn't work since the getEvents() is not called in the test function. I wanted to know how to test this function?
http://archive.msdn.microsoft.com/ewsjavaapi
Solution:
I had to mock every object being created in the function.
Also, I had to add the following above the class declaration.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ClassBeingTested.class })
I want to generate a client program using the service
I am unable to display the results, how can I do so?
import java.rmi.RemoteException;
public class searchtry {
public static void main(String[] args) throws RemoteException {
SearchRequest request=new SearchRequest();
SearchRequestType1 type1=new SearchRequestType1();
query.setAppId("*********************************"); //Windows Live gave this id for using that service
query.setSources(new SourceType[]{SourceType.Web});
query.setQuery("Java");
aratip.setParameters(request);
SearchResponseType0 answer= client.search(type1);
System.out.println(answer.toString());
}
For starters, calling
answer.toString();
May or may not result in anything (usually won't). You might just get a string that represents the instance, not the string you're expecting. You need to find a method on SearchResponseType0 that will give you the string representation of the response. Perhaps a method like getContent() or getResponse() or something like that but without understanding more about the web service it's difficult to give you more help. Bottom line, you're using the wrong method to attempt to get the string content of the result.
It looks like your are using the bing-search-java-sdk. They have a very nice example on their homepage you might want to look at:
BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
BingSearchClient client = factory.createBingSearchClient();
SearchRequestBuilder builder = client.newSearchRequestBuilder();
builder.withAppId(applicationId);
builder.withQuery("msdn blogs");
builder.withSourceType(SourceType.WEB);
builder.withVersion("2.0");
builder.withMarket("en-us");
builder.withAdultOption(AdultOption.MODERATE);
builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);
builder.withWebRequestCount(10L);
builder.withWebRequestOffset(0L);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
SearchResponse response = client.search(builder.getResult());
for (WebResult result : response.getWeb().getResults()) {
System.out.println(result.getTitle());
System.out.println(result.getDescription());
System.out.println(result.getUrl());
System.out.println(result.getDateTime());
}