2015-05-20 155 views
2

我在做單元測試和我不能編程Mockito來覆蓋部分代碼
我如何獲得Mockito回報我有效的東西?當我得到spec時,我得到一個IllegalArgumentExpection。對不起,如果這是一個無知的問題,我最近開始寫測試。
我如何嘲笑Mockito?

我的測試

@Bean 
     public SpecDBDAO getSpecDBDAO() { 
      SpecDBDAO dao = Mockito.mock(SpecDBDAO.class); 
      when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject()); 
      return dao; 
     } 

@Test 
    public void testAddLinha_validId() throws Exception { 
     planilhaService.addLinha("123", new BasicDBObject("_id", "erro")); 
    } 

我的代碼

public Planilha addLinha(String id, BasicDBObject body) { 
     String idSpec = body.getString("_id", ""); 
     Planilha planilha = specDBPlanilhasDAO.get(id); 
     if (planilha == null) { 
      throw new NotFoundException("Planilha não encontrada."); 
     } 

     try { 
      BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec))); 
      if (spec.isEmpty()) { 
       throw new NotFoundException("Especificação não encontrada."); 
      } 
      planilha.addLinha(spec); 
      planilha = specDBPlanilhasDAO.update(planilha); 

      return planilha; 
     } catch (IllegalArgumentException e) { 
      throw new BadRequestException("Id inválido."); 
     } 
    } 

覆蓋 enter image description here

+2

永遠不要爲編寫測試道歉! –

回答

2

你使用此

BasicDBObject spec = specDBDAO.findLastOne(new BasicDBObject("_id", new ObjectId(idSpec))); 
BasicDBObject實例

是不同的BasicDBObject情況下,你正在使用此

when(dao.findLastOne(new BasicDBObject("_id", "erro"))).thenReturn(new BasicDBObject()); 

解決方案

1覆蓋equals()hashCode()BasicDBObject所以平等是基於,例如,iderrno與任何一起其他值是必要的。

2使用org.mockito.Matchers類給你一個匹配,當你設置的期望,例如

when(dao.findLastOne(Matchers.any(BasicDBObject.class).thenReturn(new BasicDBObject()); 
// any BasicDBObject instance will trigger the expectation 

when(dao.findLastOne(Matchers.eq(new BasicDBObject("_id", "erro")).thenReturn(new BasicDBObject()); 
// any BasicDBObject equal to the used here instance will trigger the expectation. Equality is given by your overridden equals method 

你可以找到關於此here更多信息。