栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Junit:为删除实体的方法编写测试?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Junit:为删除实体的方法编写测试?

有两种测试策略。一种是单元测试,即确保您的服务正常运行。另一个是集成/端到端测试,即确保所有功能都能很好地协同工作。

您对自己拥有的东西进行单元测试,对所有内容进行集成测试。这是一个非常粗糙的示例,仅使用您的语句,加上一些我不能填补空白的虚构内容。

单元测试

使用Mockito

PersonRepository personRepository = mock(PersonRepository.class);@TestSubjectPersonService personService = new PersonService():@Testpublic void unitTest() {    personService.setPersonRepository(personRepository);    Person person = new Person(1L);    Person person2 = new Person(1L);    when(personRepository.returnPerson(1L)).thenReturn(person2); //expect a fetch, return a "fetched" person;    personService.deleteFromPerson(person);    verify(personRepository, times(1)).delete(person2); //pretty sure it is verify after call}

使用EasyMock …

@MockPersonRepository personRepository; //assuming it is autowired@TestSubjectPersonService personService = new PersonService():@Testpublic void unitTest() {    Person person = new Person(1L);    Person person2 = new Person(1L);    EasyMock.expect(personRepository.returnPerson(1L)).andReturn(person2); //expect a fetch, return a "fetched" person;    personRepository.delete(person2);    EasyMock.expectLastCall(); //expect a delete for person2 we plan to delete    replayAll();    personService.deleteFromPerson(person);    verifyAll(); //make sure everything was called}

是的,该测试看起来像是严格地编写的,但是无论如何,这实际上就是您正在单元测试中测试的全部内容。您希望数据库使用一个参数从数据库中获取一个Person,因此为什么会有两个

Person
对象,并且您希望删除该传递的
Person
对象,这就是您希望调用的原因。简单的方法产生简单的测试。基本上,您要确保与期望的存储库进行交互。在实际的实现中,存储库可能被破坏或为空,但这并不能改变您的服务实现正确的事实。

整合测试

另一方面,如果要进行集成测试,则不使用任何模拟。相反,您需要连接所有内容,例如 测试数据库 和存储库。由于没有实现参考,我将由您自己决定。

@Testpublic void integrationTestForAddAndDelete() {    Person person = createDummyPersonForInsertion(); //static method that creates a test Person for you    Person comparePerson;    //make sure we haven't added the person yet    Assert.assertNull(personService.getPerson(person));    //add the Person    comparePerson = personService.addPerson(person);    Assert.assertNotNull(personService.getPerson(person));    //add a rigorous compare method to make sure contents are the same, i.e. nothing is lost or transmuted incorrectly, ignoring ID if that is autogen    //alternatively, you can create a unit test just for Person    Assert.assertEquals(person, comparePerson);    //remove the Person    personService.deleteFromPerson(person);    Assert.assertNull(personService.getPerson(person));    //test for exception handling when you try to remove a non-existent person;    personService.deleteFromPerson(person);    //test for exception handling when you try to remove null    personService.deleteFromPerson(null);}

在这种情况下,您要确保您的仓​​库确实处理了该服务的所有呼叫。您知道您的服务可以通过单元测试运行,但是仓库可以通过该服务运行,或者您是否配置了错误的东西



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417582.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号