So for example, let's say I have a basic POJO like this.
例如,假設我有一個像這樣的基本POJO。
public class Stuff {
private OtherStuff otherStuff;
...
public void RunOtherStuff() {
otherStuff.run();
}
}
How exactly would you test that RunOtherStuff calls otherStuff.run?
你究竟如何測試RunOtherStuff調用otherStuff.run?
I'm using TestNG as my base testing framework right now and am completely open to any Java framework that'd allow me to test this similar to how'd you use rspec etc. in Rails and Ruby.
我現在正在使用TestNG作為我的基礎測試框架,並且對任何允許我測試它的Java框架完全開放,這與你在Rails和Ruby中如何使用rspec等類似。
2 个解决方案
#1
0
You'd create a setter for otherStuff and before you call RunOtherStuff() you'd call setOtherStuff(myFake)
你要為otherStuff創建一個setter,在你調用RunOtherStuff()之前你要調用setOtherStuff(myFake)
public class Stuff {
private OtherStuff otherStuff;
public void setOtherStuff(OtherStuff otherStuff) {
this.otherStuff = otherStuff;
}
...
public void RunOtherStuff() {
otherStuff.run();
}
}
Then your test can be written like this:
然后您的測試可以這樣寫:
private Stuff stuff;
private boolean runWasCalled;
public void setUp() {
stuff = new Stuff();
stuff.setOtherStuff(new OtherStuff() {
public void run() {
runWasCalled = true;
}
});
}
public void testThatOtherStuffRunMethodIsCalled() {
stuff.RunOtherStuff();
assertTrue(runWasCalled);
}
#2
0
Write a MockOtherStuff which is basically a subclass of OtherStuff. Override run() method and say like System.out.println('Run is called');
寫一個MockOtherStuff,它基本上是OtherStuff的子類。覆蓋run()方法並說像System.out.println('Run被調用');
Now, have a setter for OtherStuff in Stuff class and pass your mocker.
現在,在Stuff類中為OtherStuff設置一個setter並傳遞你的mocker。
EDIT:
To assert, you may have a boolean variable say runWasCalled (default to false) and set it to true inside MocOtherStuff.run()
要斷言,你可能有一個布爾變量說runWasCalled(默認為false)並在MocOtherStuff.run()中將其設置為true