获取org.mockito.exceptions.base.MockitoException:选中的异常对该方法无效!即使我抛出了正确的异常

cyej8jka  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(268)

获取org.mockito.exceptions.base.MockitoException:选中的异常对该方法无效!即使我抛出了正确的异常。我正在尝试测试这个类DecileConfigurationJsonConverter。在测试中,我在阅读DB数据时测试异常抛出场景。如果它不能读取数据库数据,它会抛出IOException,在模拟中,我确实抛出了完全相同的Exception,但我得到了上面的错误。

public class DecileConfigurationJsonConverter  implement               AttributeConverter<List<DecileParameter>,String>{
  private static final  ObjectMapper objectMapper = new ObjectMapper();
  @Override
  public List<DecileParameter> convertToEntityAttribute(String dbData) {
      if(dbData==null)
          return null;
      List<DecileParameter> dep = null;
      try
      {
          dep = objectMapper.readValue(dbData,
                  new TypeReference<List<DecileParameter>>() {});
      }
      catch (final IOException e)
      {
          return null;
      }
      return dep;
  }
}

  @RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  @AutoConfigureMockMvc
  @ActiveProfiles("dev-test")
  @TestPropertySource(locations = "classpath:application-dev-test.yml")
  @FixMethodOrder(MethodSorters.NAME_ASCENDING)
  public class UtilPackageTestMore {

  @Mock
  ObjectMapper objectMapper;

  private static void setFinalStaticField(Class<?> clazz, String fieldName, Object value)
          throws ReflectiveOperationException {

      Field field = clazz.getDeclaredField(fieldName);
      field.setAccessible(true);

      Field modifiers = Field.class.getDeclaredField("modifiers");
      modifiers.setAccessible(true);
      modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, value);
  }

  @Test
  public void TestDecileConfigurationJsonConverterExceptions() throws Exception
  {
      DecileConfigurationJsonConverter dc= new DecileConfigurationJsonConverter();
      ObjectMapper objecmapper = Mockito.mock(ObjectMapper.class);
      setFinalStaticField(DecileConfigurationJsonConverter.class, "objectMapper", objecmapper);

      List<DecileParameter> attribute = new ArrayList<>();
      attribute.add(new DecileParameter("1","2","3","4","5"));
      Mockito.when(objecmapper.writeValueAsString(attribute)).thenThrow(JsonProcessingException.class);
      String res = dc.convertToDatabaseColumn(attribute);
      assertNull(res);

      //here is the exception got thrown
      Mockito.when(objecmapper.readValue("db data",new TypeReference<List<DecileParameter>>() {})).thenThrow(java.io.IOException.class);
      List<DecileParameter> convertToEntityAttribute = dc.convertToEntityAttribute("db data");
      assertNull(convertToEntityAttribute);

  }
kknvjkwl

kknvjkwl1#

你必须抛出一个Exception,但你抛出的是一个Class<Exception>JsonProcessingException.class返回Class<Exception>示例。new JsonProcessingException()返回新的Exception示例。你只能选择后者。

Mockito.when(objecmapper.writeValueAsString(attribute))
        .thenThrow(new JsonProcessingException());

相关问题