java中+存根是什么_你究竟如何在java中存根方法或變量?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值