【问题标题】:"mvn test" did not execute @Mock annotated method“mvn test”没有执行@Mock注解的方法
【发布时间】:2021-12-05 10:49:17
【问题描述】:

我有一个如下所示的测试类:

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

public class SomeTest {
    @Mock
    Object someObj;

    @Before
    public void before() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testNullPointer() {
        Mockito.when(someObj.toString()).thenReturn("1");
    }
}

当我在这个项目的根目录下运行mvn clean test时,它说测试用例触发了NullPointerException,堆栈树显示someObj为空。
我使用的是org.mockito::mockito-core::4.0.0junit::junit::4.13.0
似乎没有执行 before() 方法。任何想法为什么?提前谢谢。

【问题讨论】:

  • 仅使用Object 类(而不是SomeMapper)可以重现吗?我之所以这么问,是因为如果是这样,我们帮助您会更简单。
  • @AlexeyR。是的,它是可重现的。我已经编辑了代码,希望对您有所帮助。
  • @AlexeyR。我发现mvn test 没有执行 before() 方法,有什么想法吗?

标签: java maven unit-testing junit mockito


【解决方案1】:

运行此测试时,您将在堆栈跟踪上方收到此错误:

testNullPointer(org.example.SomeTest)  Time elapsed: 0.368 sec  <<< ERROR!
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

这里有趣的部分是第一个项目符号 - 你不能存根 hashCode 方法。如果你用一些可以存根的方法替换它,测试就会通过。例如:

Mockito.when(someObj.toString()).thenReturn("yay!");

【讨论】:

  • Tks,这确实是个问题。但是另一个问题是mvn test没有执行@Before方法。
  • @theotheo 当我运行mvn test 时,肯定会执行@Before 方法。你能分享你的pom.xml 文件吗?也许有些东西没有正确定义。
  • 我尝试添加 pom.xml 但stackoverflow说代码太多。我想知道surefire插件是否配置不正确,org.apache.maven.plugins::maven-surefire-plugin::2.19,依赖org.apache.maven.surefire::surefire-junit3::2.19
  • @theotheo 绝对!您没有使用 JUnit 3,您使用的是 JUnit 4。IRC,您可以删除依赖项,maven-surefire-plugin 应该能够开箱即用地处理 JUnit 4
【解决方案2】:

您的班级缺少注释:

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    ...
}

【讨论】:

  • 很遗憾,问题依然存在。
猜你喜欢
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 2021-03-04
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2018-09-26
相关资源
最近更新 更多