简体   繁体   English

嘲笑:声明后,带有“ spy”注释的方法就运行了

[英]mockito : 'spy' annotated method ran once declared

I am trying to create the skeletton of a future app, using : java 8,windows 10, intelliJ, junit5, mockito. 我正在尝试使用以下方式创建未来应用程序的骨骼:java 8,windows 10,intelliJ,junit5,模拟。 I get a problem while running a test using mockito, it's the first test I write using spies, and it doesn't work. 使用模仿程序运行测试时出现问题,这是我使用间谍编写的第一个测试,并且不起作用。

It seems that the statement when(client_spy.try_to_connect(anyString(),anyInt())).thenReturn(null); 似乎该语句when(client_spy.try_to_connect(anyString(),anyInt())).thenReturn(null); leads to the execution of the method, which is not expected : I only want to tell to mockito to return null is the method try_to_connect is called. 导致该方法的执行,这是不期望的:我只想告诉try_to_connect返回的null是调用了try_to_connect方法。 Thus, the method is called in the test, and without parameters, so I get an error in this method. 因此,该方法在测试中被调用,并且没有参数,因此我在此方法中遇到错误。

here is the test class (some parts): 这是测试类(某些部分):

@ExtendWith(MockitoExtension.class)
public class unitTestsTry2 {

    private static final String LOCAL_IP = "localhost";
    private static final String REMOTE_IP = "localhost";
    private static final String LOCAL_PORT = "1001";
    private static final String REMOTE_PORT = "1002";
    private static  ApplicationRunner apr=new ApplicationRunner();

    @Spy
    ClientExtremity client_spy=new ClientExtremity();

(...)
    @Test
    void startupAndTryToConnect() {
        apr.client_endpoint = client_spy;
        when(client_spy.try_to_connect(anyString(),anyInt()))
                .thenReturn(null);  <--- THE FAULTLY LINE

        apr.main(new String[]{LOCAL_IP,LOCAL_PORT,REMOTE_IP,REMOTE_PORT});

        verify(((ClientOrders)apr.client_endpoint)).try_to_connect(REMOTE_IP,Integer.parseInt(REMOTE_PORT));

    }
}

here is my gradle file: 这是我的gradle文件:

buildscript {
    dependencies {
        classpath group: 'de.dynamicfiles.projects.gradle.plugins', name: 'javafx-gradle-plugin', version: '8.8.2'
    }
    repositories {
        mavenLocal()
        mavenCentral()

    }
}

plugins {
    id 'java'
}

group 'lorry'
version '1'

sourceCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "https://dl.bintray.com/mockito/maven" }
}

apply plugin: 'javafx-gradle-plugin'

test {
    useJUnitPlatform()

}

compileJava.dependsOn clean

jfx {
    // minimal requirement for jfxJar-task
    mainClass = 'lorry.ApplicationRunner'

    // minimal requirement for jfxNative-task
    vendor = 'YourName'

    launcherArguments = ["localhost", "1001", "localhost", "1002"]

    // gradle jfxRun
    runJavaParameter = null // String
    //runAppParameter = "localhost" "1001" "localhost" "1002" // String

    jfxMainAppJarName = "chat.jar"
}

dependencies {

    //testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'javax.websocket', name: 'javax.websocket-api', version: '1.1'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    //testImplementation('org.junit.jupiter:junit-jupiter-api:5.2.0')
    //testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.2.0')


    def final junitVersion = "5.2.0"
    compile group: 'com.google.inject', name: 'guice', version: '4.1.0'
    //compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2'
    compile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: junitVersion
    compile group: 'org.assertj', name: 'assertj-core', version: '3.9.0'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'

    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: junitVersion
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.21.0'
    testCompile 'org.mockito:mockito-junit-jupiter:2.21.0'
    testCompile group:'org.junit.jupiter',name:'junit-jupiter-api',version:  junitVersion
    testRuntime group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: junitVersion

    compile 'org.hamcrest:hamcrest-all:1.3'

    testCompile "org.testfx:testfx-core:4.0.13-alpha"
    testCompile 'org.testfx:testfx-junit5:4.0.13-alpha'

    compile group: 'org.glassfish.tyrus', name: 'tyrus-server', version: '1.13.1'
    // https://mvnrepository.com/artifact/org.glassfish.tyrus/tyrus-client
    compile group: 'org.glassfish.tyrus', name: 'tyrus-client', version: '1.13.1'


}


jar {
    baseName = 'Chat'
    version = ''
    manifest {
        attributes(
                'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
                'Main-Class': 'lorry.Chat'
        )
    }
}

EDIT thank you for your answers. 编辑感谢您的回答。 I changed my code: 我更改了代码:

@Spy
public ClientExtremity client_spy=new ClientExtremity();

@Test
void startupAndTryToConnect() {
    apr.client_endpoint = client_spy;
    when(client_spy).try_to_connect(anyString(),anyInt()).thenReturn(null);

    apr.main(new String[]{LOCAL_IP,LOCAL_PORT,REMOTE_IP,REMOTE_PORT});

    verify(((ClientOrders)apr.client_endpoint)).try_to_connect(REMOTE_IP,Integer.parseInt(REMOTE_PORT));

}

but intelliJ tells to me : Error:(73, 25) java: cannot find symbol symbol: method try_to_connect(java.lang.String,int) location: interface org.mockito.stubbing.OngoingStubbing 但是intelliJ告诉我:错误:(73,25)java:找不到符号symbol:方法try_to_connect(java.lang.String,int)位置:接口org.mockito.stubbing.OngoingStubbing

having the following clientExtremity: 具有以下clientExtremity:

@ClientEndpoint(encoders = MessageEncoder.class, decoders = MessageDecoder.class)
public class ClientExtremity implements ClientOrders {



        @OnMessage
        public void onMessage(Message message) {

        }

    @Override
    public Session try_to_connect(String remote_ip, Integer remote_port) {
        ClientManager client = ClientManager.createClient();
        Session session;
        try {
            session = client.connectToServer(ClientExtremity.class, new URI(
                    format("wss://%1$2s:%2$2d/chat",remote_ip,remote_port)
            ));
        } catch (Exception e) {
            e.printStackTrace();
            session=null;
        }
        return session;
    }
}

I can't figure out why the declaration of try_to_connect in the test method fails. 我不知道为什么测试方法中的try_to_connect声明失败。

EDIT 2 here is applicationRunner: 编辑2此处是applicationRunner:

public class ApplicationRunner {

    public static String localIP, remoteIP;
    public static int localPort, remotePort;
    public static Fenetre fenetre = new Fenetre();
    public static Session session=null;
    public static ClientExtremity client_endpoint=new ClientExtremity();

    public static void init(String[] args) {
        localIP = args[0];
        localPort = Integer.parseInt(args[1]);
        remoteIP = args[2];
        remotePort = Integer.parseInt(args[3]);

        try {
            new Thread(fenetre).start();

        } catch (Exception e) {
            e.printStackTrace();
        }

        session = ((ClientOrders) client_endpoint).try_to_connect(localIP,localPort);



    }

    public static void main (String[]args){
        init(args);

    }
}

ok, done. OK完成。 a correct code is: 正确的代码是:

@Test
    void startupAndTryToConnect() {
        ClientExtremity client_spy = spy(new ClientExtremity());
        apr.client_endpoint = client_spy;
        doReturn(null).when(client_spy).try_to_connect(anyString(), anyInt());

        apr.init(new String[]{LOCAL_IP,LOCAL_PORT,REMOTE_IP,REMOTE_PORT});

        verify(client_spy).try_to_connect(REMOTE_IP,Integer.parseInt(REMOTE_PORT));

    }

I needed to: 我需要:

  • change @spy by the method 'spy' 通过方法'spy'更改@spy
  • use doReturn/etc... instead of when/etc... 使用doReturn / etc ...而不是when / etc ...
  • in doReturn and verify, the only argument is the instance of the class, you have to write eg verify(someObjectInstance,optionalAdditionalParameters).someMethod(someArgsWithMatchers) 在doReturn和verify中,唯一的参数是该类的实例,您必须编写verify(someObjectInstance,optionalAdditionalParameters).someMethod(someArgsWithMatchers)
  • and because I do no more use @ExtendWith(MockitoExtension.class) , I had to put MockitoAnnotations.initMocks(unitTestsTry2.class); 并且因为我不再使用@ExtendWith(MockitoExtension.class) ,所以不得不放入MockitoAnnotations.initMocks(unitTestsTry2.class); in a @BeforeAll annotated method. 在@BeforeAll带注释的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM