[英]Testing an abstract class with Mockito does not give the expected result
I have a class structure similar to the following我有一个类似于以下的类结构
public abstract class AbstractStep {
private final Range RANGE;
AbstractStep(AbstractStepBuilder builder) {
RANGE = builder.range;
}
public abstract static class AbstractStepBuilder {
Range range;
public AbstractStepBuilder setRange(int start, end end) {
this.range = new Range(start, end);
return self();
}
abstract AbstractStepBuilder self();
}
public static class Range() {
private final int START;
private final int END;
private Range(int start, int end) {
if(start < 0 || end < 0 || start >= end)
throw new IllegalArgumentException();
START = start;
END = end;
}
}
}
I want to test setRange(int, int)
in AbstractStepBuilder
to see if the an IllegalArgumentException
is thrown.我想在
AbstractStepBuilder
测试setRange(int, int)
以查看是否抛出了IllegalArgumentException
。 I use TestNG and Mockito, and I have attempted the following using with the help of this .我使用 TestNG 和 Mockito,并在this的帮助下尝试了以下使用。
final class RangeTest {
AbstractStepBuilder builder;
@BeforeSuite
void setup() {
builder = Mockito.mock(AbstractStepBuilder.class);
Mockito.when(builder.self()).thenReturn(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
final void testCreatingRangeWithNegativeStart() {
builder.setRange(-1, 2);
}
}
This test fails.此测试失败。 I have also tried replacing
Mockito.mock(AbstractStepBuilder.class)
with Mockito.mock(AbstractStepBuilder.class, Mockito.CALLS_REAL_METHODS)
as in the top answer of this question.我也试过用
Mockito.mock(AbstractStepBuilder.class)
Mockito.mock(AbstractStepBuilder.class, Mockito.CALLS_REAL_METHODS)
替换Mockito.mock(AbstractStepBuilder.class)
,如这个问题的最佳答案。
Note that if I make CodeRange
as its own outer class, this test passes, so I do not believe it could be the test itself.请注意,如果我将
CodeRange
作为它自己的外部类,则此测试通过,因此我不相信它可能是测试本身。
Why is this test failing, and is it possible to fix it without having to use a concrete class in the test instead?为什么此测试失败,是否可以修复它而不必在测试中使用具体类?
You're calling a method on a mock, that will never throw an Exception until you tell it to.你在模拟上调用一个方法,除非你告诉它,否则它永远不会抛出异常。 You never mock a class you want to test.
你永远不会嘲笑你想测试的课程。
If you want to test the actual class, you'll need to create a subclass of the step builder, create an instance and test that.如果要测试实际类,则需要创建步骤构建器的子类,创建一个实例并对其进行测试。
I think you can also create a spy (by Mockito.spy(AbstractStepBuilder.class)
) to avoid creating a subclass just for the test.我认为您还可以创建一个间谍(通过
Mockito.spy(AbstractStepBuilder.class)
)以避免仅为测试创建子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.