使用Mockito.when()

时间:2016-09-13 16:39:19

标签: maven unit-testing junit powermock

我正在嘲笑一个带有最终方法的类,特别是来自jGit的RevTag类。

我需要存根两个方法的调用,我这样做(原谅愚蠢的名字):

package ut.com.isroot.stash.plugin;

import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.revwalk.RevTag;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest
public class TagProcessingStackOverflow {

    @Test
    public void testAnnotatedTagMunging() throws Exception {
        RevTag obj = mock(RevTag.class);
        PersonIdent ident = mock(PersonIdent.class);

        when(obj.getTaggerIdent()).thenReturn(ident);
        when(obj.getFullMessage()).thenReturn("lok'tar ogar \n");
    }
}

然而,对when()的第一次调用会导致NPE。为什么要执行该方法?该方法是final方法,但我认为PowerMockito可以处理这个问题。

这是我相关的pom东西:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <exclusions>
            <exclusion>
                <artifactId>hamcrest-core</artifactId>
                <groupId>org.hamcrest</groupId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.9.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.5.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.5.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
    </dependency>

0 个答案:

没有答案