如何为以下保存数据库返回的本地对象的方法编写测试用例



目前,我正在使用TestNG并尝试为以下人员编写测试用例操纵元数据(( 方法。在该方法中,元数据由存储库提供。然后根据给定的联系人列表更新元数据。

我在编写 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
}

!!

如果是,您是否也在使用 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 语法上不具体..对不起,:)

请参阅在单元测试中测试代码单元的行为。在这里,我假设您正在编写一个测试用例来检查manipulateMetaData()的行为,当metaDataReporitory.findOneByEmail(emailAddress)返回null并且您期望manipulateMetaData()将使用电子邮件地址和updateCount创建新记录。

到目前为止,您已成功模拟metaDataReporitory.findOneByEmail(emailAddress) . 接下来的步骤应该是:

  • 调用 operMetaData(( eg. Metadata metadata= metaDataHandler.manipulateMetaData(emailAddress ,contacts);
  • 现在检查操纵元数据((实际上做了什么,断言一些检查:

    assertEquals(metadata.getEmail((, emailAddress(;

  • 您还可以验证对模拟对象的调用:

    verify(mock, atMinimumOnce(((.metaDataReporitory.findOneByEmail(emailAddress(;

有关更多测试方案,请参阅此处

Mockito.when(new MetaData((.thenReturn("your mocked object"(((;

这将对您有所帮助,请谷歌更多

相关内容

  • 没有找到相关文章

最新更新