简体   繁体   English

JUnit 测试未捕获异常

[英]JUnit test not catching exception

UPDATE: Here's the full test:更新:这是完整的测试:

@Test(expected = NullPointerException.class)
public void testMissingData() throws Exception{
Resource<ObjectDataModel, Content, Status> resource = builder.build(content,  argA1Response, 
            argA2Response, objFilterParam, argA3Response);}

And here's the build method:这是构建方法:

public Resource<ObjectDataModel, Content, Status> build(Content argContent,
        ResponseA1 argA1Response,
        ResponseA2 argA2Response, String argObjectTypeFilter,
        ResponseA3 argA3Response) {

    try {
        viewDataModel.setObjectType(this.buildObjectType(filteredObjectType,
                argA1Response.getData().getDataObject().getCategories().get(0).getObjectTypes().get(0)));

    }
    catch (Exception e) {
        String msg = "Exception occoured while buildng the Object Data Model";
        LOG.error(msg, e);
    }

    // we have the required information gathered to return
    return Resource.okFromDataAndContent(viewDataModel, argContent);
}

And here's the buildObjectType() method:这是buildObjectType()方法:

private ObjectType buildObjectType(ObjectTypes argA1ProductType,
        PendingObjectTypes argA2ProductType) {
    ProductType objectType = new ObjectType();
    List<Plan> plans = argA1ObjectType.getPlan();
    List<PendingObjectSummary> objPlans = argA1ObjectType.getData();

    if (objectType.getData() == null) {
        objectType.setData(new ArrayList<>());
    }

    PendingObjectSummary tempPlan = null;
    for (Plan currPlan : plans) {
        tempPlan = plans.stream()
                        .filter(plan -> plan.getObjId().equals(currPlan.getObjId()))
                        .findFirst()
                        .orElseThrow(NullPointerException::new);

    }

    return objectType;
}

I'm using an Optional to test for null and I can confirm that the exception is being thrown -- but JUnit isn't catching it.我正在使用Optional来测试 null 并且我可以确认正在抛出异常——但 JUnit 没有捕捉到它。 Here's the test case:这是测试用例:

@Test(expected = NullPointerException.class)
public void testMissingData() throws Exception{
    Object<> response = fixture.create();

    assertNotNull(response);
    assertNotNull(response.getData());

    assertNull(resource.getData().getObjectType()); 
}

In my create method I'm simply iterating over a bunch of objects to try and find one that matches my ID;在我的create方法中,我只是遍历一堆对象来尝试找到一个与我的 ID 匹配的对象; if not found then throw a NullPointerException :如果未找到,则抛出NullPointerException

for (Object currObj : objects) {
        tempObj = myOtherCollection.stream()
                        .filter(obj -> obj.getId().equals(currObj.getId()))
                        .findFirst()
                        .orElseThrow(NullPointerException::new);
    }

The JUnit output clearly isn't catching the exception - here's the output: JUnit 输出显然没有捕获异常 - 这是输出:

java.lang.AssertionError: Expected exception: java.lang.NullPointerException

And my tomcat logs are definitely throwing the exception here:我的 tomcat 日志肯定会在这里抛出异常:

18:48:30.015 [main] ERROR com.myCompany.src.ModelBuilder - Exception occoured while buildng the Data Model
java.lang.NullPointerException: null
at java.util.Optional.orElseThrow(Optional.java:290)

The only issue I can see is that maybe where I assign tempObj that the code is wrong.我能看到的唯一问题是,也许我指定tempObj代码错误的地方。 Am I missing anything obvious?我错过了什么明显的东西吗? Thanks for any helpful tips.感谢您提供任何有用的提示。

You are catching the nullpointer exception so the exception is not propagated to your test.您正在捕获空指针异常,因此该异常不会传播到您的测试中。

see

try {
    viewDataModel.setObjectType(this.buildObjectType(filteredObjectType,
            argA1Response.getData().getDataObject().getCategories().get(0).getObjectTypes().get(0)));

}
catch (Exception e) {
    String msg = "Exception occoured while buildng the Object Data Model";
    LOG.error(msg, e);
}

If you want to test for an exception you could throw an exception in your error handling (for example a custom ObjectCreationExcepion) and assert that that one is thrown, like如果要测试异常,可以在错误处理中抛出异常(例如自定义 ObjectCreationExcepion)并断言该异常已抛出,例如

try {
    viewDataModel.setObjectType(this.buildObjectType(filteredObjectType,
            argA1Response.getData().getDataObject().getCategories().get(0).getObjectTypes().get(0)));

}
catch (Exception e) {
    String msg = "Exception occoured while buildng the Object Data Model";
    LOG.error(msg, e);
    throw new ObjectCreationException(msg);
}

and in your test在你的测试中

@Test(expected = ObjectCreationException.class) 
public void testMissingData() throws Exception{
    Object<> response = fixture.create();  
}

@Test(expected = ObjectCreationException.class) only handles exceptions that are not handled within the tested code OR the test itself. @Test(expected = ObjectCreationException.class)只处理测试代码或测试本身没有处理的异常。

So what you could do is所以你可以做的是

public Resource<ObjectDataModel, Content, Status> build(Content argContent,
        ResponseA1 argA1Response,
        ResponseA2 argA2Response, String argObjectTypeFilter,
        ResponseA3 argA3Response) throws NullPointerExceptions // << notice thrwoing declatration
{ // do some stuf} 

and then in test you can handle it like you where trying by然后在测试中,您可以像尝试一样处理它

public void testMissingData() throws Exception{
Resource<ObjectDataModel, Content, Status> resource = builder.build(content,  argA1Response, 
            argA2Response, objFilterParam, argA3Response);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM