标签: powermock

如何验证未抛出异常

在我使用Mockito的单元测试中,我想验证NullPointerException没有被抛出.

public void testNPENotThrown{
    Calling calling= Mock(Calling.class);
    testClass.setInner(calling);
    testClass.setThrow(true);

    testClass.testMethod();

    verify(calling, never()).method();
}
Run Code Online (Sandbox Code Playgroud)

我的测试设置了testClass,设置Calling对象和属性,以便该方法将抛出一个NullPointerException.

验证从不调用Calling.method().

public void testMethod(){
    if(throw) {
        throw new NullPointerException();
    }

    calling.method();
}
Run Code Online (Sandbox Code Playgroud)

我想要一个失败的测试,因为它抛出一个NullPointerException,然后我想写一些代码来解决这个问题.

我注意到的是测试总是通过,因为异常永远不会被测试方法抛出.

java mocking mockito powermock

16
推荐指数
2
解决办法
3万
查看次数

arraylength中操作数堆栈上的错误类型

我正在尝试使用powermock测试方法.我还没有写过任何测试用例.只是试图为Mocking设置课程.这是我到目前为止:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ReadRubric.class })
public class ReadRubricTest {
    @Before
    public void setUp() throws Exception {
        PowerMockito.mock(ReadRubric.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void invalidFile() throws Exception {
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此测试时,我收到以下错误.

java.lang.VerifyError: Bad type on operand stack in arraylength
    Exception Details:
      Location:
        com/cerner/devcenter/wag/processor/ReadRubric.readRubric()Ljava/util/List; @809: arraylength
      Reason:
        Invalid type: 'java/lang/Object' (current frame, stack[0])
      Current Frame:
        bci: @809
        flags: { }
        locals: { 'java/util/ArrayList', 'au/com/bytecode/opencsv/CSVReader', top, top, '[Ljava/lang/String;', 'com/cerner/devcenter/wag/processor/Rule', 'java/lang/Object', 'java/lang/Object', top, top, top, top, top, top, …
Run Code Online (Sandbox Code Playgroud)

java mocking junit4 powermock

16
推荐指数
1
解决办法
5163
查看次数

Powermock mockstatic不能继承最终类

我想嘲笑最后一堂课

PowerMockito.mockStatic(TestFinalClass.class);
Run Code Online (Sandbox Code Playgroud)

当我运行单个junit并将javaagent添加到我的VM参数时,它正在从我的eclipse开始工作

-javaagent:{path}/powermock-module-javaagent-1.6.4.jar
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用maven build命令从命令行运行所有测试用例时,我仍然得到"无法继承最终类"

下面是我从pom.xml获取的代码片段

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <argLine>-javaagent:{path}/powermock-module-javaagent-1.6.4.jar</argLine>
            </configuration>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

java eclipse junit powermock maven

16
推荐指数
1
解决办法
2万
查看次数

Mockito/PowerMocktio没有任何无效方法

我需要一个方法,在测试期间调用时返回一些什么都不做,拥有该方法的类实例作为间谍实现.

我知道doNothing()方法只适用于void方法.有没有办法通过返回某些东西的方法获得相同的行为?

谢谢!

java junit unit-testing mockito powermock

15
推荐指数
1
解决办法
1万
查看次数

Apache Spark Streaming的失败集成测试

我一直试图通过一些我为Apache Spark项目编写的单元/集成测试来追踪问题.

使用Spark 1.1.1时,我的测试通过了.当我尝试升级到1.4.0(也尝试过1.4.1)时,测试开始失败.

我已经设法将重现问题所需的代码减少到下面的小集成测试.

有趣的是,如果我在测试中注释掉@RunWith注释,那么测试就会正确通过.显然我不需要@RunWith注释来进行这种减少测试,但真正的测试相当广泛地使用了模拟,所以我宁愿不必使用PowerMock.

package com.example;

import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class SampleTest {

    @Before
    public void setup() throws Exception {
        SparkConf conf = new     SparkConf(false).setMaster("local[2]").setAppName("My app");
        JavaStreamingContext jsc = new JavaStreamingContext(conf, new Duration(1000));
    }

    @Test
    public void exampleTest() {
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我看到的例外情况

java.io.IOException: failure to login
    at org.apache.hadoop.security.UserGroupInformation.loginUserFromSubject(UserGroupInformation.java:796)
    at org.apache.hadoop.security.UserGroupInformation.getLoginUser(UserGroupInformation.java:748)
    at org.apache.hadoop.security.UserGroupInformation.getCurrentUser(UserGroupInformation.java:621)
    at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2162)
    at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2162)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.util.Utils$.getCurrentUserName(Utils.scala:2162)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:301)
    at org.apache.spark.streaming.StreamingContext$.createNewSparkContext(StreamingContext.scala:842)
    at org.apache.spark.streaming.StreamingContext.<init>(StreamingContext.scala:80) …
Run Code Online (Sandbox Code Playgroud)

java integration-testing unit-testing powermock apache-spark

15
推荐指数
1
解决办法
2437
查看次数

使用SureFire插件时遇到麻烦: - "分叉的虚拟机终止而没有说再见.虚拟机崩溃或System.exit被调用?"

在发生异常后运行单元测试时:

org.apache.maven.lifecycle.LifecycleExecutionException: ExecutionException; nested exception is java.util.concurrent.ExecutionException: java.lang.RuntimeException: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:556)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:535)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

java junit powermock maven-surefire-plugin

14
推荐指数
1
解决办法
2万
查看次数

PowerMock:如何取消模拟方法?

我有一个静态方法,使用PowerMock进行模拟以抛出异常.(它删除文件.)不幸的是,在我的@After(每次测试后)方法中,我需要在没有模拟的情况下调用此方法.我该如何摆弄方法?

我没有看到相当于Mockito.reset().[参考:mockito:如何取消模拟方法?]

例:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PathUtils.class)  // Important: This class has a static method we want to mock.
public class CleaningServiceImplTest2 extends TestBase {

    public static final File testDirPath = new File(CleaningServiceImplTest2.class.getSimpleName());

    @BeforeClass
    public static void beforeAllTests() throws PathException {
        recursiveDeleteDirectory(testDirPath);
    }

    @AfterClass
    public static void afterAllTests() throws PathException {
        recursiveDeleteDirectory(testDirPath);
    }

    private File randomParentDirPath;
    private CleaningServiceImpl classUnderTest;

    @Before
    public void beforeEachTest() {
        randomParentDirPath = new File(testDirPath, UUID.randomUUID().toString()).getAbsoluteFile();
        classUnderTest = new CleaningServiceImpl(randomParentDirPath);
    }

    @After
    public …
Run Code Online (Sandbox Code Playgroud)

java testing powermock

14
推荐指数
1
解决办法
8940
查看次数

未找到PowerMockito和Java 8 ZonedDateTime toInstant()

我运行我的测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyStuff.class)
public class MyStuffTest { ..whatever
Run Code Online (Sandbox Code Playgroud)

在我ZonedDateTime为该代码添加了类之后,它看起来失败并出现以下错误:

java.lang.IllegalStateException:无法转换名为MyCode的类原因:java.time.ZonedDateTime中找不到[source error] toInstant()

在我的代码的某处我有:

long longTimeNoSee = ZonedDateTime.parse(getateTimeString()).toInstant().toEpochMilli();
Run Code Online (Sandbox Code Playgroud)

我想这是一个错误powermock.但也许有人有点想法(?)

datetime powermock java-8

14
推荐指数
1
解决办法
3179
查看次数

PowerMock访问私有成员

阅读后:https: //code.google.com/p/powermock/wiki/BypassEncapsulation 我意识到,我不明白.

请参阅此示例:

public class Bar{
   private Foo foo;

   public void initFoo(){
       foo = new Foo();
   }
}
Run Code Online (Sandbox Code Playgroud)

如何foo使用PowerMock 访问私有成员(例如,验证它foo不是null)?

注意:
我不想要的是使用额外的get方法修改代码.

编辑:
我意识到我错过了链接页面上的示例代码块与解决方案.

解:

 Whitebox.getInternalState(bar, "foo");
Run Code Online (Sandbox Code Playgroud)

java junit private mockito powermock

14
推荐指数
1
解决办法
2万
查看次数

PowerMockito(使用Mockito)因ExceptionInInitializerError而失败

我们使用Powermockito和Mockito来模拟一些静态类.似乎java.lang.ExceptionInInitializerError每次都会抛出.

你能帮我找出问题所在吗?

正在测试的Java类

package com.myproject.myproduct.search.domain;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

public class MyQueryBuilder {

    public MultiMatchQueryBuilder getMultiMatchQueryBuilder() {
        MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery("term", "field1");
        builder.field("field1",200.9f);
        return builder;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Powermock跑步者进行Junit测试

package com.myproject.myproduct.search.domain;

import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(QueryBuilders.class)
public class MyQueryBuilderTest {

    private MyQueryBuilder myQueryBuilder;

    @Test
    public void test() {
        PowerMockito.mockStatic(QueryBuilders.class);
        MultiMatchQueryBuilder builder = PowerMockito.mock(MultiMatchQueryBuilder.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

而已.一旦我尝试模拟MultiMatchQueryBuilder,测试代码就无法运行.

这是例外:

位于org.elasticsearch.index.query.AbstractQueryBuilder的org.elasticsearch.common.ParseField.(ParseField.java:35)的org.elasticsearch.common.logging.DeprecationLogger.(DeprecationLogger.java:138)中的java.lang.ExceptionInInitializerError. (AbstractQueryBuilder.java:53)在sun.reflect.GeneratedSerializationConstructorAccessor7.newInstance(未知来源)在java.lang.reflect.Constructor.newInstance(Constructor.java:423)在org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator的.java:40)在org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:59)在org.mockito.internal.creation.jmock.ClassImposterizer.createProxy(ClassImposterizer.java:128)在org.mockito.internal.creation. jmock.ClassImposterizer.imposterise(ClassImposterizer.java:63)atg.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)org.powermock.api.mockito.internal.mockcreation.MockCreator.模拟(MockCreator.java:6 0)在org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)的com.spartasystems.stratas.search.domain.MyQueryBuilderTest.testBoostSetProperly(MyQueryBuilderTest.java:22)at sun.reflect.NativeMethodAccessorImpl.invoke0 (本地方法)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) )在org.junit的org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl $ …

java junit4 mockito powermock powermockito

14
推荐指数
1
解决办法
968
查看次数