[英]How to isolate a void print() method for testing
我写了一个长除法应用程序,我现在想测试它。 稍微简化一下,我有:简化的类
问题是如何正确使用mocks\\stubs\\spies来测试printer类的void打印方法? 我的老师说除了 outputData 和 OutputStream 之外,我不能有任何变量来测试打印机,并建议阅读有关 mockito 的内容。
假设我想用这些输入测试打印机输出的正确性:-943 和 225。我的非隔离版本如下所示:
@Test
void testPrintDivisionNegativePositiveRecurrentExpansion() {
final long VALID_INPUT_DIVIDEND = -943;
final long VALID_INPUT_DIVISOR = 225;
inputData = new InputData(VALID_INPUT_DIVIDEND, VALID_INPUT_DIVISOR);
Division division = new Division(inputData);
OutputData outputData = division.divide();
printer.print(outputData, streamOut);
String actual = streamOut.toString();
String expected = "_-943|225\r\n" + " -900|--------\r\n" + " ----|-4.19(1)\r\n" + " _-430\r\n" + " -225\r\n"
+ " ----\r\n" + " _-2050\r\n" + " -2025\r\n" + " -----\r\n" + " _-250\r\n" + " -225\r\n"
+ " ----\r\n" + " -25\r\n";
assertEquals(expected, actual);
}
我阅读了模拟和存根,但大多数示例建议使用 when().then() 并返回简单的字符串或 int,而在我的情况下 outputData 将包含每个具有 5 个字段的 List。 输出数据
我有点明白如何为此使用 spy() ,但是如果我理解正确 spy() 运行实际方法,那么依赖项仍然存在并且不会实现完全隔离。 那为什么我的测试版本更差呢?
这是您必须回答的最重要的问题。
任何其他类拥有自己的业务逻辑,您的代码与之交互都应该被模拟。
根据您的测试名称,我猜printer
对象是您的测试代码,而OutputData
是提供(对于您的测试用例)不相关业务逻辑的依赖项。 因此,您应该嘲笑:
class MyTestClass {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock OutputData outputData;
@Test
void testPrintDivisionNegativePositiveRecurrentExpansion() {
// configure mock of OutputData
printer.print(outputData, streamOut);
String actual = streamOut.toString();
String expected = "_-943|225\r\n" + " -900|--------\r\n" + " ----|-4.19(1)\r\n" + " _-430\r\n" + " -225\r\n"
+ " ----\r\n" + " _-2050\r\n" + " -2025\r\n" + " -----\r\n" + " _-250\r\n" + " -225\r\n"
+ " ----\r\n" + " -25\r\n";
assertEquals(expected, actual);
}
}
我阅读了模拟和存根,但大多数示例建议使用 when().then() 并返回简单的字符串或 int,而在我的情况下 outputData 将包含每个具有 5 个字段的 List。
当您的返回类型为 complex 或List
时,模拟没有太大区别。 您创建它的一个实例并配置您的模拟以返回:
class MyTestClass {
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock OutputData outputData;
@Test
void testPrintDivisionNegativePositiveRecurrentExpansion() {
List<YourElementType> inputData= Arrays.asList(new YourElementType(dummyValues1), new YourElementType(dummyValues2), new YourElementType(dummyValues3));
doReturn(inputData).when(outputData).getValuesToPrint();
printer.print(outputData, streamOut);
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.