[英]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这是我的服务类 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().由于 classTwo 在方法级别实例化,因此测试方法不会获取 getId()。 And I can't change or add anything to the Controller class.
我无法更改或向 Controller 类添加任何内容。 The test stops at that line and causing NullPointerException as it doesn't know the value classtwo.getId() as it is not set.
测试在该行停止并导致 NullPointerException,因为它不知道 classtwo.getId() 的值,因为它没有设置。 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.
任何可用于此的 Mockito 解决方案。
The Id in ClassTwo is an autogenerated sequence number so no need of setting in DemoClass.Java ClassTwo 中的 Id 是自动生成的序列号,因此无需在 DemoClass.Java 中设置
Here is my test class DemoClassTest.Java这是我的测试类 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
:您可以提供一个
customerRepo
测试classTwo
在classTwo
上设置一些特定的id
:
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.但是由于您似乎正在测试 JPA 代码,因此执行包含实际数据库的集成测试可能是一个更好的主意。
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.如果您想在 ClassThree 实体上断言某些内容,请在 ClassThree 存储库模拟上执行 Mockito.verify。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.