简体   繁体   中英

How to cover the Class instantiated inside a method in Mockito Junit?

How can I cover the class instantiated inside a method and need to get the value that is not set.

Here is my Service class DemoClass.Java

public class DemoClass{

 public void methodOne(){
    
    ClassTwo classTwo=new ClassTwo();
    classTwo.setName("abc");
    customerRepo.save(classTwo);
    
    ClassThree classThree=new ClassThree();
    classThree.setId(classTwo.getId()); //here causing NullPointerException as ClassTwo is instantiated inside the method and the id value is not set and the test stops here.
    classThree.setName("person1");
    classThree.setUpdatedBy("person2");

    }
}

As the classTwo is instantiated in the method level the test method does not get the getId(). And I can't change or add anything to the Controller class. The test stops at that line and causing NullPointerException as it doesn't know the value classtwo.getId() as it is not set. I need to cover that/ pass that line in the test class. I tried mocking that class and spy also. Any Mockito solutions available for this.

The Id in ClassTwo is an autogenerated sequence number so no need of setting in DemoClass.Java

Here is my test class DemoClassTest.Java

@RunWith(MockitoJunitRunner.Silent.class)
public void DemoClassTest(){

@InjectMocks
DemoClass demoClass;

@Test
public void testMethodOne(){

  demoClass.methodOne()

}

You could provide a customerRepo test double that just sets some specific id on classTwo :

public class TestCustomerRepo extends CustomerRepo {

    public void save(ClassTwo classTwo) {
        classTwo.setId(4711L);
    }
}

But since you seem to be testing JPA code it would probably be a better idea to perform an integration test containing an actual database instead.

I usually do it like this:

long testId = 123;
Mockito.when(customerRepo.save(Mockito.any())).thenAnswer(i -> {
  ClassTwo entity = (ClassTwo)invocation.getArgument(0);
  entity.setId(testId);
  return entity;
});

If you want to assert something on the ClassThree entity, do a Mockito.verify on the ClassThree repository mock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM