单元测试,用于重现和测试引发 JsonProcessingException 的方案



我有一个具有以下方法的类,我想为其编写单元测试:

public class Service {
..
..
Test getTestObj(@NotNull Product product) {
String prodJSON;
try {
prodJSON = Test.mapper.writeValueAsString(product);   // The class Test is defined as below and has the ObjectMapper property
logger.info("product json", productJSON);
} catch (JsonProcessingException e) {
logger.error("...", e);
..
throw new InternalServerErrorException("An error occured");
}
...
...
}
..
..
}

Test.java
public class Test {
public static final ObjectMapper mapper = new ObjectMapper();
..
..
}   

比方说,我有一个用于Service.java的测试类(ServiceTest.java),我想在其中为方法编写一个单元测试Test getTestObj(@NotNull Product product) {在这个单元测试中,我基本上想涵盖抛出 JsonProcessingException 的场景。所以,我希望能够测试代码:

} catch (JsonProcessingException e) {
logger.error("...", e);
throw new InternalServerErrorException("An error occured");
}

假设我从我的服务测试开始.java

@Test
public void getTestObjTest() {
Product prod = new Productt();
service.getTestObj(prod);
}

上面的测试将只涵盖不抛出 JsonProcessingException 的快乐路径。如何修改我的测试,以便在调用getTestObj时抛出JsonProcessingException?

请注意,我无法更改课程测试.java和服务.java。我只能修改我的测试

在我的测试中,我将该方法称为: service.getTestObj(prod);
所以我必须传递一个有效的产品对象。 这永远不会抛出JSONProcessingException。有没有办法用类似 new Object() 的东西操作或重置 prod 值(传递给 writeValueAsString 方法)?

public class Test {
private static final ObjectMapper mapper = new ObjectMapper();
..
..
public static ObjectMapper getMapper(){
return mapper;
}
} 

@RunWith(MockitoJUnitRunner.class)
public class JunitTest {
@Mock
private ObjectMapper mapper;
@Test(expected=InternalServerErrorException.class)
public void test(){
Mockito.when(Test.getMapper()).thenReturn(mapper);
Mockito.when(mapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class);
Service service = new Service();
service.getTestObj(new Product());
}
}

相关内容

  • 没有找到相关文章

最新更新