【问题标题】:Unit test to reproduce and test scenario that throws JsonProcessingException单元测试以重现和测试抛出 JsonProcessingException 的场景
【发布时间】:2019-04-16 02:37:12
【问题描述】:

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

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 方法)?

【问题讨论】:

  • 你需要做的是模拟你的ObjectMapper,存根它以便它抛出异常,并将其注入Test。您需要更改 Test.java 以允许这样做。我知道你说过你不能,但你必须重新审视这一点。 (不确定您不允许更改的单元测试代码的值是什么 - 如果测试失败,您会怎么做?)

标签: java spring junit jackson mockito


【解决方案1】:
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());

            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2021-09-21
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多