英文:
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<Exception>`. `JsonProcessingException.class` returns a `Class<Exception>` 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't need to mock anything at all here. Try to avoid Reflection. Keep your tests simple and don'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<DecileParameter> convertToEntityAttribute = dc.convertToEntityAttribute("INVALID_JSON"); // value can be anything that cannot be deserialized
assertNull(convertToEntityAttribute);
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论