目前,我正在使用TestNG并尝试编写测试用例 manipulateMetaData()方法。在该方法中,metaData由存储库提供。然后根据给定的联系人列表更新metaData。
我在为manipulateMetaData()方法编写测试用例时卡住了。
public class MetaData {
String email;
Map<String, Integer> count = new HashMap<>();
public void setEmail(String email) {
this.email = email;
}
public void updateCount(List<String> contact) {
// perform the calculation and update the count.
}
}
public class MetaDataHandler {
@Autowired
MetaDataRepository metaDataRepository;
public MetaData manipulateMetaData(String emailAddress, List<String> contact) {
MetaData metaData = metaDataRepository.findOneByEmail(emailAddress);
if (metaData == null) {
metaData = new MetaData();
metaData.setEmail(emailAddress);
}
metaData.updateCount(contact);
return metaData;
}
}
测试用例
@Mock
MetaDataRepository metaDataReporitory;
@InjectMocks
MetaDataHandler metaDataHandler = new MetaDataHandler();
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testManipulateMetaData() {
List<String> contact = new ArrayList<>();
String emailAddress = "someone@gmail.com";
Mockito.when(metaDataReporitory.findOneByEmail(emailAddress)).thenReturn(null);
//Stuck Here
//Want to test manipulateMetaData() method
}
答案 0 :(得分:0)
Mockito.when(新的MetaData()。thenReturn(“你的模拟对象”)));
这会对你有所帮助,请谷歌更多
答案 1 :(得分:0)
!!
你是否正在使用maven如果是,那么你应该在prom.xml
中提供依赖项你必须在编写测试用例时传递电子邮件地址和自定义列表,并在编写jUnit测试用例时将该值传递给函数。
String email="xyz@yahoo.com"; //your email custom here you can take value from scanner also just declare the scanner object and take value from user .
List<String> contact = new LinkedList<String>; //declaration of linklist
//now write code here to take some value from the user (like we normally take some value and insert it into the list )
//once list value is inserted do ...
Metadata meta_test = null ; // take obj of metadata as you have made a return type
meta_test= manipulateMetaData(email, contact); //call that function
//if return we get is null that means nothing is inserted in meta_test and it must show red while testing and if not null that means test case is successful :)
if(meta_test != null)
{
asserttrue(true);
}
else
{
assertrue(false);
}
//希望,我解决了你的问题,我可能在某些地方没有具体的术语od语法..srry for that :)
答案 2 :(得分:0)
在单元测试中查看您测试代码单元的行为。在这里,我假设您正在编写一个测试用例,以便在manipulateMetaData()
返回metaDataReporitory.findOneByEmail(emailAddress)
时检查null
的行为,并且您希望manipulateMetaData()
将使用电子邮件地址和updateCount创建新记录。
到目前为止,您已成功模拟metaDataReporitory.findOneByEmail(emailAddress)
。接下来的步骤应该是:
Metadata metadata= metaDataHandler.manipulateMetaData(emailAddress ,contacts);
现在检查一下manipulateMetaData()实际上做了什么,断言一些 检查:
assertEquals(metadata.getEmail(),emailAddress);
您还可以验证模拟对象上的调用:
验证(mock,atLeastOnce())。metaDataReporitory.findOneByEmail(emailAddress);
更多测试场景请参阅this