Getting org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Even though I am throwing correct exception

huangapple go评论63阅读模式
英文:

Getting org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Even though I am throwing correct exception

问题

以下是您提供的代码的翻译:

获得 org.mockito.exceptions.base.MockitoException
此方法无效的已检查异常尽管我正在抛出正确的异常我正在尝试测试此类 DecileConfigurationJsonConverter在测试中我正在测试读取数据库数据时抛出异常的场景如果无法读取数据库数据它会抛出 IOException而在模拟中我确实抛出了完全相同的异常但我收到了上述错误

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);
  }
}
英文:

Getting org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method! Even though I am throwing correct exception. I am trying to test this class DecileConfigurationJsonConverter. In the test I am testing the exception throw scene while reading DB data. Its throws IOException if it cant read DB data and in the mock I did throw the exact same Exception yet I got the above error.

  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);
}   

答案1

得分: 1

你必须抛出一个`Exception`,但你正在抛出一个`Class<Exception>`。 `JsonProcessingException.class`返回一个`Class<Exception>`实例。 `new JsonProcessingException()`返回一个新的`Exception`实例。你只能抛出后者。

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

但实际上,在这里你根本不需要模拟任何东西。尽量避免使用反射。保持你的测试简单,不要将它们与你的实现耦合。

public class DecileConfigurationJsonConverter
    implements AttributeConverter<List<DecileParameter>, String> {
  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  @Override
  public List<DecileParameter> convertToEntityAttribute(final String dbData) {
      if (dbData==null) return null;
      try
      {
          return OBJECT_MAPPER.readValue(dbData,
                  new TypeReference<List<DecileParameter>>() {});
      }
      catch (final IOException e)
      {
          return null;
      }
  }
}

public class UtilPackageTestMore {

  @Test
  public void TestDecileConfigurationJsonConverterExceptions() throws Exception
  {
      final DecileConfigurationJsonConverter dc = new DecileConfigurationJsonConverter();

      final List<DecileParameter> convertToEntityAttribute = dc.convertToEntityAttribute("INVALID_JSON"); // value can be anything that cannot be deserialized
      assertNull(convertToEntityAttribute);

  }
}   

<details>
<summary>英文:</summary>
You must throw an `Exception`, but you are throwing a `Class&lt;Exception&gt;`. `JsonProcessingException.class` returns a `Class&lt;Exception&gt;` instance. `new JsonProcessingException()` returns a new `Exception` instance. You can only throw the latter.

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


But in fact you don&#39;t need to mock anything at all here. Try to avoid Reflection. Keep your tests simple and don&#39;t couple them to your implementation.

public class DecileConfigurationJsonConverter
implements AttributeConverter<List<DecileParameter>, String> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

@Override
public List<DecileParameter> convertToEntityAttribute(final String dbData) {
if (dbData==null) return null;
try
{
return OBJECT_MAPPER.readValue(dbData,
new TypeReference<List<DecileParameter>>() {});
}
catch (final IOException e)
{
return null;
}
}
}

public class UtilPackageTestMore {

@Test
public void TestDecileConfigurationJsonConverterExceptions() throws Exception
{
final DecileConfigurationJsonConverter dc = new DecileConfigurationJsonConverter();

  final List&lt;DecileParameter&gt; convertToEntityAttribute = dc.convertToEntityAttribute(&quot;INVALID_JSON&quot;); // value can be anything that cannot be deserialized
assertNull(convertToEntityAttribute);

}
}


</details>

huangapple
  • 本文由 发表于 2023年5月28日 13:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定