我在测试中使用了TestNG和Mock。出现了一个困惑的问题,我在网上搜索了很长时间。我需要你的帮助。。。亲爱的
我想对这种方法进行测试
@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;
}
我尝试了以下方法:
@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());
}
前三个还可以,但最后一个报告了错误。
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.
我在网上搜索。答案都是关于何时(方法(模拟((,关于我的问题没有答案。请帮帮我~
您不能在这些 Mockito 调用中混合匹配器和正态变量。换句话说,使用 Matchers.eq( areaName )
而不是 areaName
.一旦使用一个匹配器,就不能再使用正常值了。要么所有参数都是匹配器,要么没有
完全可以:
when(something( myVariable1, myVariable2, "string", 4)).then(...);
when(something( any(), any(), eq("string"), eq(4)).then(...);
不行:
when(something( any(), any(), "string", 4).then(...);