单元测试以重现并测试抛出JsonProcessingException的场景

时间:2019-04-16 02:37:12

标签: java spring junit jackson mockito

我有一个要使用以下方法编写的单元测试类:

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

让我们说我从ServiceTest.java开始

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

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

请注意,我不能更改类Test.java和Service.java。我只能修改测试

在测试中,我将该方法称为: service.getTestObj(prod);
因此,我必须传递一个有效的Product对象。 而且永远不会抛出JSONProcessingException。有没有办法使用诸如new Object()之类的东西来操纵或重置prod值(传递给writeValueAsString方法)?

1 个答案:

答案 0 :(得分:0)

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

            }
        }