我认为功能
是
按照您期望的顺序执行,这只是一个如何以及何时显示输出的问题。
我刚刚复制并粘贴了您的源代码,并添加了一个
counter
变量,当我运行它时,我会看到以下输出:
Setup Performed... 0
In given...1
...CleanUp Performed... 2
Setup Performed... 3
In given...4
...CleanUp Performed... 5
Setup Performed... 6
In given...7
...CleanUp Performed... 8
RequiresSetupCalculator
如果在执行操作之前没有设置,并且如果我们在没有调用之前尝试运行设置,则会引发异常
cleanUp
.
public class RequiresSetupCalculator {
private static RequiresSetupCalculator instance;
private int result = 0;
private double result1 = 0;
private boolean isSetup;
private RequiresSetupCalculator() {
}
public static synchronized RequiresSetupCalculator setup() {
if (instance == null) {
instance = new RequiresSetupCalculator();
}
if (instance.isSetup) {
throw new RuntimeException("I have already been set up");
}
instance.isSetup = true;
return instance;
}
public void cleanUp() {
if (!isSetup) {
throw new RuntimeException("I wasn't set up in the first place");
}
isSetup = false;
}
public void add(final int arg1,
final int arg2) {
if (!isSetup) {
throw new RuntimeException("I haven't been set up, no calculating for you!");
}
result = arg1 + arg2;
}
public int getResult() {
if (!isSetup) {
throw new RuntimeException("I haven't been set up, no calculating for you!");
}
return result;
}
public void subtract(final int arg1,
final int arg2) {
if (!isSetup) {
throw new RuntimeException("I haven't been set up, no calculating for you!");
}
result1 = arg2 - arg1;
}
public double getresult1() {
if (!isSetup) {
throw new RuntimeException("I haven't been set up, no calculating for you!");
}
return result1;
}
}
Calculator
,然后修改
CalculatorSteps
使用
并致电
setup
和
清理
@Before
@After
您的测试方法如下:
public class CalculatorSteps {
private RequiresSetupCalculator calculator;
@Before
public void setUp() {
calculator = RequiresSetupCalculator.setup();
System.out.println("Setup Performed...");
}
... (existing test steps unchanged)...
@After
public void cleanUp() {
System.out.println("CleanUp Performed...");
calculator.cleanUp();
}
}
@之前
@之后
方法在每次测试后运行,也只有一次。
对我来说,这是成功的。如果在运行测试时抛出异常,那么会发生一些奇怪的事情,但我很有信心您会得到与我相同的结果。