【问题标题】:JUnit, JMock, JUnitRuleMockery: what am I missingJUnit,JMock,JUnitRuleMockery:我错过了什么
【发布时间】:2014-03-21 21:15:18
【问题描述】:

这很奇怪:我使用 JMockJMock 有一段时间了,它总是工作得很好:在测试结束时检查期望值,如果有一个(或更多) 丢失了测试失败。但是,这个 sn-p 在 Eclipse 中对我不起作用(DAOorg.mongodb.morphia.dao.DAO 中描述的接口):

  @Rule public JUnitRuleMockery context = new JUnitRuleMockery();

  private DAO<Cobrand, ObjectId> dao = context.mock(DAO.class);
  private final Retriever service = new Retriever(dao);

  @Test
  public void canRetrieveASinglePropertyValue () throws NoSuchFieldException, IllegalAccessException
  {
    context.checking(new Expectations()
    {
      {
        oneOf(dao).findOne("cobrand", "cobrandName"); will(returnValue(prepareFakeCobrand("cobrandName")));
        oneOf(dao).findOne("cobrand", "cobrandName"); will(returnValue(prepareFakeCobrand("cobrandName")));
      }
    });

    String value = service.getValue("cobrandName", "property");

    assertThat(value, equalTo("value"));

    //context.assertIsSatisfied();
  }

当我说“不工作”时,我的意思是我必须取消注释行 context.assertIsSatisfied(); 才能看到测试失败(在 Eclipse 中,我将此类作为 Junit 测试运行)。为了完整起见,这是代码service.getValue,其中findOne 显然只调用了一次:

public String getValue (String cobrandName, String property)
{
  Cobrand cobrand = cobrandDAO.findOne("cobrand", cobrandName);
  return "value";
}

我正在使用Gradle 来管理我的构建,如果我执行命令gradle clean test 并注释context.assertIsSatisfied(); 行,则测试失败。这是我的build.gradle

dependencies {
  def hamcrestVersion = "1.3"
  def jmockVersion = "2.6.0"

  compile 'org.mongodb.morphia:morphia:0.106'

  testCompile "org.hamcrest:hamcrest-core:${hamcrestVersion}"
  testCompile "org.hamcrest:hamcrest-library:${hamcrestVersion}"
  testCompile "org.jmock:jmock:${jmockVersion}"
  testCompile "org.jmock:jmock-junit4:${jmockVersion}"
  testCompile 'junit:junit:4.11'
}

我做错了什么?我可以做些什么来检查为什么 Eclipse 中的 Run As -> JUnit test 在通过 gradle clean test 执行相同的代码工作(测试失败)时没有按预期运行?

【问题讨论】:

标签: java eclipse junit gradle jmock


【解决方案1】:

我终于找到了问题。
正如jeremyjjbrown 在他的评论中所建议的那样,问题确实与类路径有关,但与Eclipse-Gradle plugin 及其导入项目的方式有关。
我如何解决问题

  1. 在 Eclipse 中删除了项目
  2. 进入终端,在项目源文件夹中
  3. 输入gradle cleanEclipse
  4. 输入gradle eclipse
  5. 在Eclipse中,导入Import之后的项目->Existing Projects into Workspace

这确实解决了问题,但是我无法直接在 Eclipse 中管理 Gradle(即我不能 right click -> Gradle -> Refresh All),因为该项目没有 Gradle 特性。将其转换为 Gradle 项目使原来的问题又回来了。所以,最后,

我是如何真正解决问题的
查看我的gradle.build,可以看到testCompile "org.jmock:jmock-junit4:2.6.0"。 jMock 有一个微妙的问题:它带来了junit-dep:4.4。 Eclipse 中的这种依赖关系导致了问题,将相关的 jar 插入到类路径中。将testCompile 行更改为

testCompile ("org.jmock:jmock-junit4:${jmockVersion}") {
  exclude group:"junit"
}

确实解决了问题。

感谢pbanfi,他亲自帮助我调试并真正解决了问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多