簡體   English   中英

JUnit,JMock,JUnitRuleMockery:我錯過了什么

[英]JUnit, JMock, JUnitRuleMockery: what am I missing

這很奇怪:我使用JUnitJMock使用Rule JUnitRuleMockery一段時間它總是很好地工作:在測試結束時檢查的期望以及如果一個(或多個)丟失測試失敗。 但是,這段代碼在Eclipse中org.mongodb.morphia.dao.DAODAOorg.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執行時相同的代碼工作(測試失敗)時表現不正常?

我終於找到了問題。
這個問題確實與類路徑有關,正如jeremyjjbrown在他的評論中所建議的那樣,但它與Eclipse-Gradle插件及其導入項目的方式有關。
我是怎么解決這個問題的

  1. 在Eclipse中刪除了該項目
  2. 轉到終端,在項目源文件夾中
  3. 鍵入gradle cleanEclipse
  4. 打字的gradle eclipse
  5. 在Eclipse中,將Import - > Existing Projects into Workspace 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親自幫助我調試並解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM