Using Mockito to mock out Spring Boot repository delete call throws java.util.NoSuchElementException on get()












0















I am new to Spring Boot and Mockito and having a problem mocking out a repository call in my service test.



I have a "delete" service method call as follows that I am trying to test with Mockito by mocking out the repository calls:



public interface IEntityTypeService {
public EntityType getById(long id);
public EntityType getByName(String name);
public List<EntityType> getAll();
public void update(EntityType entityType);
public void delete(long id);
public boolean add(EntityType entityType);
}

@Service
public class EntityTypeServiceImpl implements IEntityTypeService {
@Autowired
private EntityTypeRepository entityTypeRepository;

@Override
public void delete(long id) {
entityTypeRepository.delete(getById(id));
}

@Override
public EntityType getById(long id) {
return entityTypeRepository.findById(id).get();
}

....implementation of other methods from the interface
}


My repository looks as follows:



@RepositoryRestResource
public interface EntityTypeRepository extends LookupObjectRepository<EntityType> {

}


I have not implemented any of the methods in the repository as I am letting Spring Boot wire it up for me.



My test is as follows:



@RunWith(SpringRunner.class)
public class EntityTypeServiceTest {
@TestConfiguration
static class EntityTypeServiceImplTestContextConfiguration {

@Bean
public IEntityTypeService entityTypeService() {
return new EntityTypeServiceImpl();
}
}

@Autowired
private IEntityTypeService entityTypeService;
@MockBean
private EntityTypeRepository entityTypeRepository;

@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Mockito.when(entityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
assertThat(entityTypeRepository.findById(1L).get()).isNull();
}
}


When I run the test, I get an error saying "java.util.NoSuchElementException: No value present"



java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at xyz.unittests.service.EntityTypeServiceTest.whenDelete_thenObjectShouldBeDeleted(OriginatingEntityTypeServiceTest.java:41)


It references the line in the test saying Mockito.when(originatingEntityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);



The reason I think I have to mock that call out is because the delete method in the Service calls the getById() method in the same service, which in turn calls entityTypeRepository.findById(id).get()



It is that, that I am assuming I have to mock out on the delete. But clearly I am wrong. Any assistance would be appreciated.



Many thanks










share|improve this question

























  • Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

    – bittu
    Nov 21 '18 at 9:42
















0















I am new to Spring Boot and Mockito and having a problem mocking out a repository call in my service test.



I have a "delete" service method call as follows that I am trying to test with Mockito by mocking out the repository calls:



public interface IEntityTypeService {
public EntityType getById(long id);
public EntityType getByName(String name);
public List<EntityType> getAll();
public void update(EntityType entityType);
public void delete(long id);
public boolean add(EntityType entityType);
}

@Service
public class EntityTypeServiceImpl implements IEntityTypeService {
@Autowired
private EntityTypeRepository entityTypeRepository;

@Override
public void delete(long id) {
entityTypeRepository.delete(getById(id));
}

@Override
public EntityType getById(long id) {
return entityTypeRepository.findById(id).get();
}

....implementation of other methods from the interface
}


My repository looks as follows:



@RepositoryRestResource
public interface EntityTypeRepository extends LookupObjectRepository<EntityType> {

}


I have not implemented any of the methods in the repository as I am letting Spring Boot wire it up for me.



My test is as follows:



@RunWith(SpringRunner.class)
public class EntityTypeServiceTest {
@TestConfiguration
static class EntityTypeServiceImplTestContextConfiguration {

@Bean
public IEntityTypeService entityTypeService() {
return new EntityTypeServiceImpl();
}
}

@Autowired
private IEntityTypeService entityTypeService;
@MockBean
private EntityTypeRepository entityTypeRepository;

@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Mockito.when(entityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
assertThat(entityTypeRepository.findById(1L).get()).isNull();
}
}


When I run the test, I get an error saying "java.util.NoSuchElementException: No value present"



java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at xyz.unittests.service.EntityTypeServiceTest.whenDelete_thenObjectShouldBeDeleted(OriginatingEntityTypeServiceTest.java:41)


It references the line in the test saying Mockito.when(originatingEntityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);



The reason I think I have to mock that call out is because the delete method in the Service calls the getById() method in the same service, which in turn calls entityTypeRepository.findById(id).get()



It is that, that I am assuming I have to mock out on the delete. But clearly I am wrong. Any assistance would be appreciated.



Many thanks










share|improve this question

























  • Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

    – bittu
    Nov 21 '18 at 9:42














0












0








0








I am new to Spring Boot and Mockito and having a problem mocking out a repository call in my service test.



I have a "delete" service method call as follows that I am trying to test with Mockito by mocking out the repository calls:



public interface IEntityTypeService {
public EntityType getById(long id);
public EntityType getByName(String name);
public List<EntityType> getAll();
public void update(EntityType entityType);
public void delete(long id);
public boolean add(EntityType entityType);
}

@Service
public class EntityTypeServiceImpl implements IEntityTypeService {
@Autowired
private EntityTypeRepository entityTypeRepository;

@Override
public void delete(long id) {
entityTypeRepository.delete(getById(id));
}

@Override
public EntityType getById(long id) {
return entityTypeRepository.findById(id).get();
}

....implementation of other methods from the interface
}


My repository looks as follows:



@RepositoryRestResource
public interface EntityTypeRepository extends LookupObjectRepository<EntityType> {

}


I have not implemented any of the methods in the repository as I am letting Spring Boot wire it up for me.



My test is as follows:



@RunWith(SpringRunner.class)
public class EntityTypeServiceTest {
@TestConfiguration
static class EntityTypeServiceImplTestContextConfiguration {

@Bean
public IEntityTypeService entityTypeService() {
return new EntityTypeServiceImpl();
}
}

@Autowired
private IEntityTypeService entityTypeService;
@MockBean
private EntityTypeRepository entityTypeRepository;

@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Mockito.when(entityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
assertThat(entityTypeRepository.findById(1L).get()).isNull();
}
}


When I run the test, I get an error saying "java.util.NoSuchElementException: No value present"



java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at xyz.unittests.service.EntityTypeServiceTest.whenDelete_thenObjectShouldBeDeleted(OriginatingEntityTypeServiceTest.java:41)


It references the line in the test saying Mockito.when(originatingEntityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);



The reason I think I have to mock that call out is because the delete method in the Service calls the getById() method in the same service, which in turn calls entityTypeRepository.findById(id).get()



It is that, that I am assuming I have to mock out on the delete. But clearly I am wrong. Any assistance would be appreciated.



Many thanks










share|improve this question
















I am new to Spring Boot and Mockito and having a problem mocking out a repository call in my service test.



I have a "delete" service method call as follows that I am trying to test with Mockito by mocking out the repository calls:



public interface IEntityTypeService {
public EntityType getById(long id);
public EntityType getByName(String name);
public List<EntityType> getAll();
public void update(EntityType entityType);
public void delete(long id);
public boolean add(EntityType entityType);
}

@Service
public class EntityTypeServiceImpl implements IEntityTypeService {
@Autowired
private EntityTypeRepository entityTypeRepository;

@Override
public void delete(long id) {
entityTypeRepository.delete(getById(id));
}

@Override
public EntityType getById(long id) {
return entityTypeRepository.findById(id).get();
}

....implementation of other methods from the interface
}


My repository looks as follows:



@RepositoryRestResource
public interface EntityTypeRepository extends LookupObjectRepository<EntityType> {

}


I have not implemented any of the methods in the repository as I am letting Spring Boot wire it up for me.



My test is as follows:



@RunWith(SpringRunner.class)
public class EntityTypeServiceTest {
@TestConfiguration
static class EntityTypeServiceImplTestContextConfiguration {

@Bean
public IEntityTypeService entityTypeService() {
return new EntityTypeServiceImpl();
}
}

@Autowired
private IEntityTypeService entityTypeService;
@MockBean
private EntityTypeRepository entityTypeRepository;

@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Mockito.when(entityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
assertThat(entityTypeRepository.findById(1L).get()).isNull();
}
}


When I run the test, I get an error saying "java.util.NoSuchElementException: No value present"



java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at xyz.unittests.service.EntityTypeServiceTest.whenDelete_thenObjectShouldBeDeleted(OriginatingEntityTypeServiceTest.java:41)


It references the line in the test saying Mockito.when(originatingEntityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);



The reason I think I have to mock that call out is because the delete method in the Service calls the getById() method in the same service, which in turn calls entityTypeRepository.findById(id).get()



It is that, that I am assuming I have to mock out on the delete. But clearly I am wrong. Any assistance would be appreciated.



Many thanks







spring-boot mockito






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 9:34







Keith Davies

















asked Nov 21 '18 at 9:00









Keith DaviesKeith Davies

52




52













  • Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

    – bittu
    Nov 21 '18 at 9:42



















  • Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

    – bittu
    Nov 21 '18 at 9:42

















Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

– bittu
Nov 21 '18 at 9:42





Well entityTypeRepository.findById(1L) is not yet mocked and we called get() on that.

– bittu
Nov 21 '18 at 9:42












1 Answer
1






active

oldest

votes


















0














@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Optional<EntityType> optionalEntityType = Optional.of(entity);
Mockito.when(entityTypeRepository.findById(1L)).thenReturn(optionalEntityType);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
//I dont think you need to assert to confirm actual delete as you are testing mock registry. to assert somethink like below you need to return null by mocking the same call again and return the null but thats of no use
//assertThat(entityTypeRepository.findById(1L).get()).isNull();
}


Updated your test. Basically we first need to mock the result of findById. refer my comment above asserting the actual delete.






share|improve this answer
























  • Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

    – Keith Davies
    Nov 22 '18 at 15:24











  • On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

    – Keith Davies
    Nov 22 '18 at 15:31













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408431%2fusing-mockito-to-mock-out-spring-boot-repository-delete-call-throws-java-util-no%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Optional<EntityType> optionalEntityType = Optional.of(entity);
Mockito.when(entityTypeRepository.findById(1L)).thenReturn(optionalEntityType);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
//I dont think you need to assert to confirm actual delete as you are testing mock registry. to assert somethink like below you need to return null by mocking the same call again and return the null but thats of no use
//assertThat(entityTypeRepository.findById(1L).get()).isNull();
}


Updated your test. Basically we first need to mock the result of findById. refer my comment above asserting the actual delete.






share|improve this answer
























  • Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

    – Keith Davies
    Nov 22 '18 at 15:24











  • On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

    – Keith Davies
    Nov 22 '18 at 15:31


















0














@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Optional<EntityType> optionalEntityType = Optional.of(entity);
Mockito.when(entityTypeRepository.findById(1L)).thenReturn(optionalEntityType);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
//I dont think you need to assert to confirm actual delete as you are testing mock registry. to assert somethink like below you need to return null by mocking the same call again and return the null but thats of no use
//assertThat(entityTypeRepository.findById(1L).get()).isNull();
}


Updated your test. Basically we first need to mock the result of findById. refer my comment above asserting the actual delete.






share|improve this answer
























  • Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

    – Keith Davies
    Nov 22 '18 at 15:24











  • On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

    – Keith Davies
    Nov 22 '18 at 15:31
















0












0








0







@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Optional<EntityType> optionalEntityType = Optional.of(entity);
Mockito.when(entityTypeRepository.findById(1L)).thenReturn(optionalEntityType);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
//I dont think you need to assert to confirm actual delete as you are testing mock registry. to assert somethink like below you need to return null by mocking the same call again and return the null but thats of no use
//assertThat(entityTypeRepository.findById(1L).get()).isNull();
}


Updated your test. Basically we first need to mock the result of findById. refer my comment above asserting the actual delete.






share|improve this answer













@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Optional<EntityType> optionalEntityType = Optional.of(entity);
Mockito.when(entityTypeRepository.findById(1L)).thenReturn(optionalEntityType);

// when
entityTypeService.delete(entity.getID());

// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
//I dont think you need to assert to confirm actual delete as you are testing mock registry. to assert somethink like below you need to return null by mocking the same call again and return the null but thats of no use
//assertThat(entityTypeRepository.findById(1L).get()).isNull();
}


Updated your test. Basically we first need to mock the result of findById. refer my comment above asserting the actual delete.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 21 '18 at 9:55









bittubittu

347110




347110













  • Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

    – Keith Davies
    Nov 22 '18 at 15:24











  • On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

    – Keith Davies
    Nov 22 '18 at 15:31





















  • Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

    – Keith Davies
    Nov 22 '18 at 15:24











  • On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

    – Keith Davies
    Nov 22 '18 at 15:31



















Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

– Keith Davies
Nov 22 '18 at 15:24





Thank you bittu. Much appreciated. On your comment regarding not needing the assert. It makes sense, but if I remove it, all I am testing is that the delete method is called once. Seems like too basic a test really. But perhaps that is all I need to do as the repository test should be the one testing that it is actually deleted from the DB. I am just testing my logic here.

– Keith Davies
Nov 22 '18 at 15:24













On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

– Keith Davies
Nov 22 '18 at 15:31







On a related, but different note, whilst I have your (or anybody elses) attention, do you by any chance know of a good example project I can pull from Github that uses Spring Boot with the normal tiers (domain, repository, service, controller) and has testing (unit and integration) with mocking? I feel like this is something we all encounter and it would be great to have a "template" upon which to learn from somebody else? Of course my use case is different, but that patterns will apply.

– Keith Davies
Nov 22 '18 at 15:31




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408431%2fusing-mockito-to-mock-out-spring-boot-repository-delete-call-throws-java-util-no%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

MongoDB - Not Authorized To Execute Command

How to fix TextFormField cause rebuild widget in Flutter

Npm cannot find a required file even through it is in the searched directory