java - 单元测试中的反射(reflection)

标签 java junit

此方法从 person 对象获取一个值,并将该值转换为新值并返回它。

public String function(Person person)
{
   List<Activities> activities= person.getListOfActivities();
   String value1= "";
   for (Activities ac: activities) 
     {
            Bungee1 bun1= (Bungee1) ac;
            value1= bun1.getValue();
      }
    String convertedValue = "";
    if (!value1.isEmpty()) 
       {
     convertedValue= convert(value1);
       } 
  return convertedValue;
  }

此测试用例正在检查assertEquals(expectedValue,actualValue)

@Test
public void testFunction()
 {
     Person person = setHardCodedValuestoPersonObject();

     Method method  =ABC.class.getDeclaredMethod("funtion", Person.class);
     method.setAccessible(true);
     String actualValue= (String)method.invoke(new ABC(), person);

      assertEquals(expectedValue,actualValue);  
  }

此方法仅在测试类中,用于将硬编码值设置为对象

 public void setHardCodedValuestoPersonObject()
  {
     Student student= new Student();
      student.setName("Sahil");
      student.setAge(27);
      student.setPlace("California");
    Activities activities = setList();
      student.setListOfActivities(activities); 
    return student;

   }

该方法用于设置对象列表的值

  public void setList()
    { 
      Person person = new Person();
       person.setId(getId());--->123
       person.setValue1(getRandomValue());--->124
    return person;
     }

这是我需要编写单元测试的方法。我需要 检查预期值和实际值。

问题是预期值会改变,它会增加,如果我 更改 setList() 中 setters 方法的顺序

for e.g. 
person.setValue1()---> its value 123 
person.setId()--->124). 

那么如何在testCase中添加expectedValue以便我可以获得不同的值 按照顺序。我以为我们硬编码 ExpectedValue,但就我而言,expectedValue 会改变。怎么添加呢?

我还有一个问题:我可以在单元测试中使用 Reflection 的 invoke() 两次吗 相同的方法还是不同的方法?

提前致谢。

最佳答案

您要测试的代码块必须执行单个特定的操作。

如果做得正确,则无需验证 100 个甚至 10 个其他值。每个测试测试一个逻辑概念,这就是为什么我们每个测试都有一个断言。所以你的想法是正确的

I thought we hardcode expectedValue

因此,始终考虑更好的测试,而不是针对多个值运行它。

虽然直接运行私有(private)方法不是最佳实践,但每当有此类需要时我都会使用 Whitebox.invokeMethod() 并且可以多次调用它。这里是 PowerMockito 用户。

关于java - 单元测试中的反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188550/

相关文章:

intellij-idea - Cucumber runner 类的 Intellij IDEA 运行配置

java - 想要一个 JUnitMatchers AssertThat 来测试包含 3 个或更多子字符串的字符串(当前使用 assertThat ... ... 和 ...)

java - Junit4 : expected=Exception not working with SPRING

java - 当我将具有 "HH"模式的日期字符串传递给 SimpleDateFormat 时,为什么会返回日期?

java - 使用具有字符串资源的枚举填充 Spinner

java - Spring Autowire重复问题

java - 使用java获取 cucumber 中未定义的场景和步骤

java - Gradle 无法使用 useJUnitPlatform() 运行 JUnit 测试

Java文本分析程序

java - 用于 Retrofit2 回调的 JSON 中的 POJO 类