2015-04-30 26 views
1

我正在嘗試測試dropwizard資源並遵循http://www.dropwizard.io/manual/testing.html這樣做。Mockito在測試dropwizard資源時總是返回null

但是,我總是從模擬類/方法中得到一個空對象。

資源方法

@GET 
    @Path("/id") 
    @ApiOperation("Find property by id") 
    @Produces(MediaType.APPLICATION_JSON) 
    public Property findById(@QueryParam("id") int id) { 

     return propertyDAO.findById(id); 
    } 

,並且測試類

public class PropertiesResourceTest { 

    private static final PropertiesDAO dao = mock(PropertiesDAO.class); 

    @ClassRule 
    public static final ResourceTestRule resources = ResourceTestRule.builder() 
      .addResource(new PropertiesResource(dao)) 
      .build(); 

    private final Property property = new Property(1); 

    @Before 
    public void setUp() { 

     when(dao.findById(eq(1))).thenReturn(property); 
     reset(dao); 
    } 

    @Test 
    public void findById() { 
     assertThat(resources.client().target("/properties/id?id=1").request().get(Property.class)) 
       .isEqualTo(property); 
     verify(dao).findById(1); 
    } 

} 

我試着旋轉它在許多方面,但結果總是相同的:

expected:<Property | ID: 1 > but was:<null> 

你h對於爲什麼mockito總是返回一個空對象的任何線索?

回答

2
when(dao.findById(eq(1))).thenReturn(property); 
reset(dao); 

第一行存根調用findById。第二行,reset,immediately deletes that stubbing您可能想要交換這兩個語句的順序。

雖然保持嘲笑在靜態變量是一個危險的習慣,雖然該文件是正確的,建議你手動調用reset,它這樣做你設置的期望之前是重要(即在你@第一線在方法之前)或在測試完成後(即作爲@After方法的最後一行)。否則,Mockito將不會在那裏找到存根,並會返回默認值null

我建議您按照他們的建議刪除static修飾符,並使用@Rule而不是@ClassRule。不經意間造成測試污染的可能性很小。

這是非常奇怪的是,你鏈接的文檔有代碼示例與順序的方法。它可能應該更新。

+0

嗯,我覺得這封信的文件是愚蠢的...無論如何,它的工作原理。謝謝 ! –