return Mono.just(key) //
.map(Service1::doSomething) //
.map(Service2:: doSomething) //
.map(Service3::getBytes);
My code is as above, I have many logs in the methods of services (Service1, Service2 and Service3), so I can confirm that those methods are not called, till I call subscribe method by manually verifying the log files. Are there any testing tools which can help me automate that testing?
Mokito can track invocations using mocks/spys. Here's an example using Spring:
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
#RunWith(SpringRunner.class)
public class ExampleTests {
#SpyBean
private Service1 service1;
#SpyBean
private Service2 service2;
#SpyBean
private Service3 service3;
#Test
public void verifyNothingHappensWithoutSubscribe() {
Mono.just("key")
.map(service1::doSomething)
.map(service2::doSomething)
.map(service3::getBytes);
verify(service1, times(0)).doSomething("key");
verify(service2, times(0)).doSomething("key");
verify(service3, times(0)).getBytes("key");
}
#Test
public void verifyCallsWhenSubscribed() {
Mono<byte[]> testMono = Mono.just("key")
.map(service1::doSomething)
.map(service2::doSomething)
.map(service3::getBytes);
StepVerifier.create(testMono)
.expectNextCount(1)
.verifyComplete();
verify(service1, times(1)).doSomething("key");
verify(service2, times(1)).doSomething("key");
verify(service3, times(1)).getBytes("key");
}
}
Related
I am trying to run parallel test through selenium grid.
I know I have to use "thread local" for parallel execution,
but I have a problem with my code.
Cannot invoke "io.appium.java_client.android.AndroidDriver.findElementByAccessibilityId(String)" because "driver" is null
can you please solve it
package appiumset;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class _2_Deviceinfo {
public ThreadLocal<AppiumDriver> driver = new ThreadLocal<>();
public void setDriver(AppiumDriver driver) {
this.driver.set(driver);
}
public AppiumDriver getDriver() {
return this.driver.get();
}
#Parameters({"device", "apppackage", "activity","version","appiumServer" , "systemPort", "platformName"})
#BeforeMethod
public synchronized void deviceSetUp(String device, String apppackage, String activity, String version, String appiumServer, String systemPort, String platformName) throws InterruptedException, MalformedURLException {
System.out.println("****************************************");
System.out.println("Setting up device and desired capabilities");
DesiredCapabilities cap = new DesiredCapabilities();
URL url = new URL(appiumServer);
setDriver(new AndroidDriver<>(url, cap));
cap.setCapability(MobileCapabilityType.DEVICE_NAME, device);
cap.setCapability(MobileCapabilityType.UDID, device);
cap.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, systemPort);
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120);
cap.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
//cap.setCapability(MobileCapabilityType., BrowserType.ANDROID);
cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version);
cap.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, apppackage);
cap.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, activity);
cap.setCapability("automationName", "UiAutomator2");
cap.setCapability("noReset","false");
cap.setCapability("FullReset","true");
cap.setCapability("APP_WAIT_ACTIVITY", "*");
cap.setCapability("autowebview","false");
}
#AfterMethod
public void closeDriver() {
getDriver().quit();
}
}
I can't find the driver (AppiumDriver)
package appiumset;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
public class _3_Onboarding extends _1_Appstart {
#Test
public void onboarding() throws MalformedURLException, InterruptedException {
System.out.println("_3_Onboarding Start");
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();
System.out.println("next-done");
}
}
call getdriver() method of your class _2_Deviceinfo to your test class.
Appiumdriver<?> driver = getDriver();
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();
I am trying to call server side function from client using littemplate. I have checked examples on Vaadin site and found that client may call server side via this.$server._some_method.
I tried to use $server in littemplate but during frontend compilation vaadin throws error stating that "Property '$server' does not exist on type 'HelloWorld'."
Please let me know what is wrong with this program and guide me.
Thank you.
Littemplate
import {LitElement, html} from 'lit-element';
import '#vaadin/vaadin-button/vaadin-button.js';
class HelloWorld extends LitElement {
render() {
return html`
<div>
<vaadin-button id="helloButton">Click me!</vaadin-button>
</div>`;
}
sayHello(){
showNotification("Hello");
this.$server.greet(); //Problematic statement.
}
}
customElements.define('hello-world', HelloWorld);
Java
package com.example.application.littemplate;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.littemplate.LitTemplate;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.template.Id;
import com.vaadin.flow.component.textfield.TextField;
//HelloWorld.java
#Tag("hello-world")
#JsModule("./views/littemplate/hello-world.ts")
public class HelloWorld extends LitTemplate {
#Id
// Uses the vaadin-button id "helloButton"
private Button helloButton;
public HelloWorld() {
helloButton.addClickListener(event -> Notification.show("Hello " + nameField.getValue()));
}
#ClientCallable
public void greet() {
System.out.println("Hello server");
}
}
Typescript does not know that LitTemplate has a $server variable. You have to define it yourself.
You can use type any or define your interface.
For example:
private $server?: MyTestComponentServerInterface;
And add the #ClientCallable functions:
interface MyTestComponentServerInterface {
greet(): void;
}
In your case, your typescript could be:
import {LitElement, html} from 'lit-element';
import '#vaadin/vaadin-button/vaadin-button.js';
class HelloWorld extends LitElement {
private $server?: HelloWorldServerInterface;
render() {
return html`
<div>
<vaadin-button id="helloButton">Click me!</vaadin-button>
</div>`;
}
sayHello(){
showNotification("Hello");
this.$server!.greet(); // should work with autocompletion
}
}
interface HelloWorldServerInterface {
greet(): void;
}
customElements.define('hello-world', HelloWorld);
I am new to Appium and just getting started, I would like to call methods from other classes by creating an object. but when I call methods it show "this.driver" is null. how to call methods from other class by creating object?? is it possible?? Noted that: I already use 'extends class', so I didn't use it in multiple classes.
//Here, I call methods from other classes......
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
//import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
#Test(priority = 11)
public void IncompleteTask() {
String ser="Update For Testing";
Searching(ser);
AllMethods scr=new AllMethods(driver);
scr.Scroll();
//Scroll();
Point point1=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getCenter();
Point point2=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getLocation();
Swipping(point1,point2);
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_reAssign").click();
//driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/noButton").click();
String mass=driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/tvMessage").getText();
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
String mText="Are you sure you want to undo this Task?";
if(mass.contains(mText))
{
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
}
System.out.println("IncompleteTask Executed!");
driver.quit();
}
//Here is my allMethods class
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.support.PageFactory;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.io.IOException;
import java.lang.NullPointerException;
public class AllMethods {
public AndroidDriver<AndroidElement> driver;
public AllMethods(AndroidDriver driver)
{
PageFactory.initElements(driver, this);
}
public void searching(String ser) {
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_search").click();
driver.findElementById("android:id/search_src_text").sendKeys(ser);
driver.hideKeyboard();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void Scroll() throws NullPointerException
{
for(int i=0; i<3; i++)
{
Dimension dimension=driver.manage().window().getSize();
int start_x=(int) (dimension.width*0.5);
int start_y=(int) (dimension.height*0.2);
int end_x=(int) (dimension.width*0.5);
int end_y=(int) (dimension.height*0.8);
TouchAction tcD=new TouchAction(driver);
tcD.press(PointOption.point(start_x,
start_y)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2)))
.moveTo(PointOption.point(end_x, end_y)).release().perform();
}
}
}
The methods in AllMethods class are referring to the driver which is not yet initialized. i.e they are referring to this driver :
public AndroidDriver<AndroidElement> driver;
You will need to add this.driver=driver inside AllMethods constructor, this will set the driver with the reference of the driver that is passed in the constructor.
I have a plugin with jenkins version set to 1.580.3.And when I upgrade the jenkins version to 1.642.3<=version , it is throwing a null pointer exception.Below is the stacktrace
java.lang.NullPointerException
at hudson.model.Label.hashCode(Label.java:528)
at java.util.HashMap.hash(HashMap.java:338)
at java.util.HashMap.put(HashMap.java:611)
at java.util.HashSet.add(HashSet.java:219)
at java.util.Collections.addAll(Collections.java:5401)
at com.google.common.collect.Sets.newHashSet(Sets.java:183)
at com.ericsson.oss.axis.ATest.setUp(ATest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
below is my code
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.jenkins.plugins.nodelabelparameter.LabelParameterValue;
import org.mockito.Answers;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.XXXXX.JenkinsUtils;(internal)
import com.google.common.collect.Sets;
import hudson.model.AbstractBuild;
import hudson.model.Label;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import jenkins.model.Jenkins;
#RunWith(PowerMockRunner.class)
#PrepareForTest( JenkinsUtils.class)
public class A{
#Mock
private Label label;
#Mock
private Jenkins jenkins;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
private AbstractBuild build;
#Before
public void setUp() {
PowerMockito.mockStatic(JenkinsUtils.class);
try {
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(NodeLabelParameterUtils.class )
public class B{
private BaselineDefinedMessageDispatcher unit;
private BuildData buildData = new BuildData();
private MyBuildDetails myBuildDetails;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
private AbstractBuild build;
#Mock
private BuildLogger buildLogger;
#Mock
private Label label;
#Mock
private Computer computer;
#Mock
private PretendSlave node;
#Mock
private FreeStyleProject project;
#Mock
private Jenkins jenkins;
#Mock
private EnvironmentVariableResolver envVarsResolver;
#Before
public void setUp() throws IOException, InterruptedException, Descriptor.FormException {
unit = spy(new BaselineDefinedMessageDispatcher(null, null));
unit.setBuildLogger(mock(BuildLogger.class));
MyBuildDetails = mock(MyBuildDetails.class);
doReturn("expectedSlaveHost").when(unit).getHostNameFromSlave(any(Node.class));
doReturn(project).when(build).getProject();
doReturn(Sets.<Node>newHashSet(node)).when(label).getNodes();
doReturn(node).when(build).getBuiltOn();
doReturn(jenkins).when(unit).getJenkinsInstance();
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
PowerMockito.mockStatic(A.class);
when(envVarsResolver.processString(anyString())).thenAnswer(new Answer<String>() {
#Override
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
return (String) invocationOnMock.getArguments()[0];
}
});
}
The following dependencies are being used
powermock-api-mockito - 1.6.3
mockito-core - 1.9.5
junit - 4.11
java - 1.8
jenkins.version - 1.642.3
I get the error exactly at doReturn(Sets.newHashSet(label)).when(jenkins).getLabels(); in class A.
This is a maven project and when jenkins version is set to 1.580.3 mvn clean install is success but when it is version>=1.642.3 it is failing.
My aim is to upgrade jenkins verison to 2.X.I went through manyworkarounds in stackoverflow but nothing worked
Any help is appreciated
Edit:
Looks like my orignal answer was just incorrect.
The NPE comes from the fact that the abstract Label class has a constructor parameter called name. This parameter is used to calculate the hashcode of the label.
If you mock it this name is null and you get the NPE.
The question now is do you need to create a mock of this or can you actually use a real instance? In the exmaple below I just used one of the implementations of that class LabelAtom. If a mock is required because you need to define some behaviour on the object that you can not get otherwise, you probably have to use a spy.
(Tested with org.jenkins-ci.main:jenkins-core:2.85)
import static org.mockito.Mockito.doReturn;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import com.google.common.collect.Sets;
import hudson.model.Label;
import hudson.model.labels.LabelAtom;
import jenkins.model.Jenkins;
#RunWith(PowerMockRunner.class)
public class Test {
#Mock
private Jenkins jenkins;
private Label label;
#Before
public void setUp() {
Assert.assertNotNull(jenkins);
label = new LabelAtom("someName");
// or if a mock is required
//label = Mockito.spy(new LabelAtom("someName"));
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
}
#Test
public void test() {
}
}
Regarding the WithOrWithoutExpectedArguments I was not able to reproduce that one.
I tried displaying the google web page on my javafx view using webview. All it does is display an empty page. For testing I did add a text element at the bottom and it did show up. Any pointers would be helpful. My code and the sample screen are attached.
I am running this application on a Windows 7 machine with 8 GB RAM and this is deployed in an environment that needs proxy authentication.
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class MyBrowser extends Application
{
private Pane root;
#Override
public void start(final Stage stage) throws URISyntaxException
{
root = new VBox();
List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com"));
final Proxy proxy = proxies.get(0); // ignoring multiple proxies to simplify code snippet
if (proxy.type() != Proxy.Type.DIRECT)
{
// you can change that to dialog using separate Stage
final TextField login = new TextField("login");
final PasswordField pwd = new PasswordField();
Button btn = new Button("Login");
btn.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent t)
{
System.setProperty("http.proxyUser", login.getText());
System.setProperty("http.proxyPassword", pwd.getText());
displayWebView();
}
});
root.getChildren().addAll(login, pwd, btn);
}
else
{
displayWebView();
}
stage.setScene(new Scene(root, 400, 600));
stage.show();
}
private void displayWebView()
{
root.getChildren().clear();
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
root.getChildren().addAll(webView, new Text("HELLO"));
webEngine.load("http://www.google.com");
}
public static void main(String[] args)
{
launch();
}
}
I copied and pasted your code and ran it on Windows 7 with Java7u40 both Java8b108.
In both cases the code functioned correctly and displayed the http://www.google.com page.
The proxy selector code in your source was not triggered for me (probably because I have a Proxy.Type.DIRECT connection, so there was nothing for it to do).