2

我有 catch 块,我想执行 catch 块。我的班级文件是,

    public class TranscoderBean implements TranscoderLocal {
    public byte[] encode(final Collection<?> entitySet) throws TranscoderException {
        Validate.notNull(entitySet, "The entitySet can not be null.");
        LOGGER.info("Encoding entities.");
        LOGGER.debug("entities '{}'.", entitySet);

        // Encode the Collection
        MappedEncoderStream encoderStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            // Create the encoder and write the the DSE Logbook messgae
            encoderStream = new MappedEncoderStream(outputStream, this.encoderVersion);
            encoderStream.writeObjects(new ArrayList<Object>(entitySet), false);
            encoderStream.flush();
        }
        catch (Exception e) {
            LOGGER.error("Exception while encoding entities", e);
            throw new TranscoderException("Failed to encode entities", e);
        }
        finally {
            if (encoderStream != null) {
                try {
                    encoderStream.close();
                }
                catch (IOException e) {
                    LOGGER.error("Exception while closing the endcoder stream.", e);
                    throw new TranscoderException("Failed to close encoder stream", e);
                }
            }
        }
     }

我的测试类文件是,

public class TranscoderBeanTest {

    private TranscoderBean fixture;

    @Mock
    MappedEncoderStream mappedEncoderStream;
    @Test
    public void encodeTest() throws TranscoderException {
        List<Object> entitySet = new ArrayList<Object>();
        FlightLog log1 = new FlightLog();
        log1.setId("F5678");
        log1.setAssetId("22");

        FlightLog log2 = new FlightLog();
        log2.setId("F5679");
        log2.setAssetId("23");
        entitySet.add(log1);
        entitySet.add(log2);

        MockitoAnnotations.initMocks(this);
        try {
            Mockito.doThrow(new IOException()).when(this.mappedEncoderStream).close();

            Mockito.doReturn(new IOException()).when(this.mappedEncoderStream).close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] encode = this.fixture.encode(entitySet);
        Assert.assertNotNull(encode);
    } 
}

我已经尝试过 Mockito.doThrow 和 Mockito.doReturn 方法,但仍然没有执行 catch 块。做错了什么。

4

3 回答 3

0

你期望 Mockito 做它没有声称做的事情:

Mockito.doThrow(new IOException()).when(this.mappedEncoderStream).close();

该语句断言,每当有人调用close()mapperEncoderStream-Object 时,都会收到一个IOException. 你从不打电话close

尝试mapperEncoderStream.close();在您的 Mockito-actions 之后添加,然后将输入 catch 块 - 但请注意:这不会帮助您解决问题,因为 mockito 在这里无法提供帮助。

对于您的问题,您可以考虑以下替代方案:

改写

encoderStream = new MappedEncoderStream(outputStream, this.encoderVersion);

encoderStream = createMappedEncoderStream(outputStream);

MappedEncoderStream createMappedEncoderStream(ByteArrayOutputStream outputStream) {
  return new MappedEncoderStream(outputStream, this.encoderVersion);
}

这使您可以将模拟作为依赖项注入。

然后像这样初始化你的fixture:

fixture = new TranscoderBean() {
  MappedEncoderStream createMappedEncoderStream(ByteArrayOutputStream outputStream) {
    return mappedEncoderStream; //this is your mock
  }
}

这会将模拟注入到您的 TranscoderBean.encode 方法中。

然后更改您的模拟注释:

@Mock(answer=CALLS_REAL_METHODS)
MappedEncoderStream mappedEncoderStream;

这是必需的,因为您的 encode 方法不仅调用closeon mappedEncoderStream,而且调用writeObjectsand flush。这些调用可能会抛出异常,因此它们必须被模拟或替换为对真实对象的调用。

像这样修剪你的测试

@Test(expected=TranscoderException.class)
public void encodeTest() throws TranscoderException {
    //... same as above
    MockitoAnnotations.initMocks(this);
    Mockito.doThrow(new IOException()).when(this.mappedEncoderStream).close();

     this.fixture.encode(entitySet); //this will throw an exception
}

这将执行以下操作:

  • 编码方法不返回null!它抛出 a TranscoderException,所以它被放置为expected
  • close用异常抛出覆盖方法
  • 调用编码
于 2015-04-06T14:03:12.277 回答
0

你确定你有正确的测试类。我在您的文件中没有看到对 TranscoderBean 的任何引用

于 2015-04-02T06:52:56.073 回答
0

要测试 try-catch 块,您可以使用 TestNG 方法,该方法包括使用以下注释实现测试方法expectedExceptions。这个方法的代码,你必须实现它才能引发这个异常,所以catch块会被执行。

你可以看看http://testng.org/doc/documentation-main.html#annotations

于 2015-04-02T06:48:30.727 回答