【问题标题】:Mock not recognized in IntelliJ while using Scala使用 Scala 时在 IntelliJ 中无法识别 Mock
【发布时间】:2012-08-08 18:47:07
【问题描述】:
@RunWith(classOf[MockitoJUnitRunner])
class ScalaTest {

  var x  = mock[java.util.Map]
  val y  = mock[ClassA]
  val z  = mock[ClassB]
}

无论我在我的 pom 文件中设置什么依赖项,我都无法让 Mock 工作。编译器只是说无法解析符号MockClassOf。我在下面显示了我的依赖项:

<dependency>
  <groupId>org.scalamock</groupId>
  <artifactId>scalamock-scalatest-support_${scala.version}</artifactId>
  <version>2.4</version>
</dependency>
<dependency>
  <groupId>org.scalamock</groupId>
  <artifactId>scalamock-junit3-support_${scala.version}</artifactId>
  <version>2.4</version>
</dependency>

而测试依赖是:

<dependency>
  <groupId>org.scalatest</groupId>
  <artifactId>scalatest_${scala.version}</artifactId>
  <version>2.0.M3</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>1.9.0</version>
  <scope>test</scope>
</dependency>

这些是我的导入:

import org.junit.{Test, Before}
import org.junit.runner.RunWith
import org.mockito.runners.MockitoJUnitRunner

有什么建议吗??

【问题讨论】:

  • 你的例子很不完整。我没有看到类 MockitoJUnitRunner 的导入。此外,MockitoJUnitRunner 甚至不包含在您的依赖项中。也许您想添加 org.mockito:mockito-all:1.8.5 作为依赖项?当然,mock 无法解析,因为您没有导入任何可以提供它的对象。
  • @StefanEndrullis:我已经编辑了帖子以显示导入。我也有我现在添加到上面的帖子中的 mockito 依赖项。我希望这有助于理解它。我仍然无法让它工作。

标签: unit-testing scala mocking


【解决方案1】:

我不知道 mockito 但根据

你的 ScalaTest 类应该扩展一个单元套件并且应该混入 MockitoSugar(它提供了 mock 方法)。

如果 classOf 无法在您的注释声明 RunWith 中解析,您可能必须使用更新的 Scala 版本(2.8 或更高版本)。

【讨论】:

    【解决方案2】:

    您正在为 ScalaTest 和 JUnit 导入 ScalaMock 支持类,但您根本没有使用 ScalaTest(您正在使用带有自定义运行器的 JUnit,我不熟悉)并且似乎正在使用根据 Stefan 对 yoru question 的评论,一组错误的特征。

    如果您想使用 ScalaTest 作为您的测试运行器,您应该将相关套件类之一与 MockitoSugar 混合使用(遵循 ScalaTest documentation):

    // First, create the mock object
    val mockCollaborator = mock[Collaborator]
    
    // Create the class under test and pass the mock to it
    classUnderTest = new ClassUnderTest
    classUnderTest.addListener(mock)
    
    // Use the class under test
    classUnderTest.addDocument("Document", new Array[Byte](0))
    classUnderTest.addDocument("Document", new Array[Byte](0))
    classUnderTest.addDocument("Document", new Array[Byte](0))
    classUnderTest.addDocument("Document", new Array[Byte](0))
    
    // Then verify the class under test used the mock object as expected
    verify(mockCollaborator).documentAdded("Document")
    verify(mockCollaborator, times(3)).documentChanged("Document")
    

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      相关资源
      最近更新 更多