首页 > 解决方案 > 对构造函数方法进行单元测试

问题描述

我很难理解如何对构造函数方法进行单元测试。

我需要检查是否引发了错误。构造函数是:

@Autowired
public BankDetailsValidator() {
  try {
    logDebugMessage("BankDetailsValidator() constructor");
    loadModulusWeightTable();
    loadSortCodeSubstitutionTable();
  } catch (final IOException e) {
    throw new BankDetailsValidationRuntimeException("An error occured loading the modulus weight table or sort code substitution table", e);
  }
}

要对此进行测试,我需要使用loadModulusWeightTableor loadSortCodeSubstitutionTablethrow and IOException

private void loadModulusWeightTable() throws IOException {
  modulusWeightTable.clear();
  logDebugMessage("Attempting to load modulus weight table " + MODULUS_WEIGHT_TABLE);

  final InputStream in = new FileInputStream(MODULUS_WEIGHT_TABLE);
  br = new BufferedReader(new InputStreamReader(in));
  try {
    String line;
    while ((line = br.readLine()) != null) {
      final String[] fields = line.split("\\s+");
      modulusWeightTable.add(new ModulusWeightTableEntry(fields));
    }
    logDebugMessage("Modulus weight table loaded");
  }
  finally {
    br.close();
  }
}

我试图让Spy缓冲文件阅读器返回 aIOException但由于它位于构造函数中而无法使其工作。

public class BankDetailsValidatorTest {

  @Spy
  private BufferedReader mockBufferReader;

  @InjectMocks
  private CDLBankDetailsValidator testSubject;

  @Test(expected = IOException.class)
  public void testIOErrorLogging() throws Exception{

    when(mockBufferReader.readLine()).thenThrow(new IOException());
    testSubject = new CDLBankDetailsValidator();
  }
}

标签: javajunit4

解决方案


我认为应该重构 BankDetailsValidator 类。在这种情况下,您应该将负责读取数据的代码提取到单独的类中,并将其作为构造函数参数注入 BankDetailsValidator。之后,您可以单独测试该阅读器,当然还可以使用模拟阅读器测试 BankDetailsValidator。


推荐阅读