【问题标题】:How to cover the Class instantiated inside a method in Mockito Junit?如何覆盖在 Mockito Junit 中的方法内实例化的类?
【发布时间】:2021-12-10 22:28:50
【问题描述】:

如何覆盖方法内部实例化的类,需要获取未设置的值。

这是我的服务类 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");

    }
}

由于 classTwo 在方法级别实例化,因此测试方法不会获取 getId()。而且我无法更改或向 Controller 类添加任何内容。测试在该行停止并导致 NullPointerException 因为它不知道值 classtwo.getId() 因为它没有设置。我需要在测试课中覆盖/通过那条线。 我也试着嘲笑那个班级和间谍。任何可用于此的 Mockito 解决方案。

ClassTwo 中的 Id 是自动生成的序列号,所以不需要在 DemoClass.Java 中设置

这是我的测试类 DemoClassTest.Java

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

@InjectMocks
DemoClass demoClass;

@Test
public void testMethodOne(){

  demoClass.methodOne()

}

【问题讨论】:

  • 如何自动生成?
  • @Id @GeneratedValue() private Long id;
  • 但是在调用 getId() 之前您没有保存 ClassTwo。只有在持久化实体时才会发生自动生成
  • 你错过了......添加
  • 您可以提供一个customerRepo 测试替身,它只是在classTwo 上设置一些特定的id...

标签: java spring-boot unit-testing junit mockito


【解决方案1】:

您可以提供一个customerRepo 测试替身,它只是在classTwo 上设置一些特定的id

public class TestCustomerRepo extends CustomerRepo {

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

但由于您似乎正在测试 JPA 代码,因此执行包含实际数据库的集成测试可能是一个更好的主意。

【讨论】:

    【解决方案2】:

    我通常这样做:

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

    如果您想在 ClassThree 实体上声明某些内容,请在 ClassThree 存储库模拟上执行 Mockito.verify。

    【讨论】:

    • 这里在 entity.setId(testId) 处得到 NullPointerException
    • 请分享您的完整测试
    猜你喜欢
    • 2023-02-09
    • 2019-09-18
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多