Rajat Gupta
Rajat Gupta

Reputation: 33

Junit error - No value present or no such element

testclass.java

@Test
public void testgetDictionaryValueListById() {

    DictionaryValue dictionaryValue = new DictionaryValue();
    dictionaryValue.setId(1);
    dictionaryValue.setValueName("Test Dictionary Value");
    dictionaryValue.setValueKey("12345678");
    dictionaryValue.setStatus("Active");
    dictionaryValue.setCreatedOn(new Date());
    dictionaryValue.setUpdatedOn(new Date());

    Mockito.when(dictionaryValueRepo.findById(1).get()).thenReturn(dictionaryValue);
    assertThat(dictionaryService.getDictionaryValueListById(1)).isEqualTo(dictionaryValue);

}

Service.java

public DictionaryValue getDictionaryValueListById(int id) {
    return dictionaryValueRepo.findById(id).get();
}

Repo.java

@Repository
public interface DictionaryValueRepo extends JpaRepository<DictionaryValue, Integer> {

}

I am getting no such value present again and again on executing test case in testclass.java. I don't know why? but when I am running my service method from the controller it is working as expected - fetching records from the database but not working in a test case.

Upvotes: 0

Views: 1346

Answers (2)

LenglBoy
LenglBoy

Reputation: 1441

Your test should be like this and please check out the naming. You need to Mock the step findId() befor the `get().

@InjectMocks
Service cut;

@Mock
DictionaryValueRepo dictionaryValueRepoMock;

// Can skipped by adding a @RunWith... on Testclass
@Before
public init() {
    Mockito.initMocks(this);
}

@Test
public void testgetDictionaryValueListById() {

    // Prepare Data
    final int testId = 1;
    DictionaryValue dictionaryValue = new DictionaryValue();
    dictionaryValue.setId(testId);
    dictionaryValue.setValueName("Test Dictionary Value");
    dictionaryValue.setValueKey("12345678");
    dictionaryValue.setStatus("Active");
    dictionaryValue.setCreatedOn(new Date());
    dictionaryValue.setUpdatedOn(new Date());

    // config mocking
    Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(<VALUE>);
    Mockito.when(dictionaryValueRepo.findById(testId).get()).thenReturn(dictionaryValue);

    // Call yout method for Testing
    cut.getDictionaryValueListById(testId);

    // verifies (if wanted) + assertions....
}

Upvotes: 1

Jhilton
Jhilton

Reputation: 405

I concur with LenglBoy, so the right answer should be given to him.

The thing you need to be careful is what "VALUE" means in this line:

Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(VALUE);

The findById returns an Optional, so that is what you should build and pass to Mockito. Something like this:

    Mockito.when(dictionaryValueRepo.findById(testId))
         .thenReturn(Optional.ofNullable(dictionaryValue));

And for a scenario where the id does not exists in BD, passing Optional.empty() should be good enough.

Upvotes: 0

Related Questions