vendredi 16 mars 2018

java:use mock parameters in generic method,it makes error

I used TestNG and Mock in test.It occured a confused problem,and I had searched for a long time on net.I need your help...Dear

I want to do test for this method

@Override
public boolean addAreaToDB(String areaName, Integer areaCode) {
   if (isAreaExists(areaCode)) {
     return false;
   }
   Area area = new Area(areaCode, areaName);
   areaDao.save(area);
   onlineDiskService.initFoldersAndPrime(areaCode);
   return true;
}

I tried the following ways :

  @InjectMocks
  private AreaServiceImpl areaService;
  @Mock
  private IAreaDAO areaDao;
  @Mock
  private OnlineDiskService onlineDiskService;

  @BeforeTest
  public void before() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testAddAreaToDB() {
    String areaName="";
    Integer areaCode=0;

    //first:
    Area area = new Area();
    when(areaDao.getByAreaCode(anyInt())).thenReturn(area);
    areaService.addAreaToDB(areaName, areaCode);

    //second:
    when(areaDao.getByAreaCode(anyInt())).thenReturn(area);
    areaService.addAreaToDB(anyString(), areaCode);

    //third:
    when(areaDao.getByAreaCode(anyInt())).thenReturn(area);
    areaService.addAreaToDB(areaName, anyInt());

    //forth:
    when(areaDao.getByAreaCode(anyInt())).thenReturn(area);
    areaService.addAreaToDB(anyString(), anyInt());
  }

The first three is ok,but the last reported an error.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 2 recorded:
-> at 

com.tal.peiyoupad.service.impl.AreaServiceImplTest.testAddAreaToDB(AreaServiceImplTest.java:69) -> at com.tal.peiyoupad.service.impl.AreaServiceImplTest.testAddAreaToDB(AreaServiceImplTest.java:69)

This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

I searched the net.Answers are all about when(method(Mock)),there is no answer about my problem.Help me,please~

Aucun commentaire:

Enregistrer un commentaire