問題描述
我正在嘗試監(jiān)視一個對象,并且我想在構(gòu)造函數(shù)調(diào)用它之前存根由構(gòu)造函數(shù)調(diào)用的方法.
我的班級是這樣的:
I'm trying to spy on an Object and I want to stub a method that is called by the constructor before the constructor calls it.
My class looks like that:
public class MyClass {
public MyClass() {
setup();
}
public void setup() {
}
}
不得調(diào)用 setup 方法.那么,我如何監(jiān)視這個方法(以及存根設(shè)置,使其什么都不做)?
它可以很好地模擬該方法,但我想對 MyClass
進行單元測試,所以我需要其他方法.
The setup method mustn't be called. Well, how do I spy on this method (and stub setup so that it does nothing)?
It works fine with mocking the method but I want to unit test MyClass
and so I will need very other method.
為什么需要存根設(shè)置方法以使其不執(zhí)行任何操作:
我正在編寫樂高機器人(lejos),并在設(shè)置中放置了一些機器人需要工作的代碼.但是,當我在 TinyVM(安裝在機器人上的 VM)之外調(diào)用它時,java 崩潰,因為它沒有正確初始化 VM(因為測試在我的 PC 上運行).對于單元測試,設(shè)置并不重要.
我不能存根類/方法設(shè)置調(diào)用,因為其中一些是公共靜態(tài)最終變量.
The reason why need to stub the setup method so that it does nothing:
I'm programing a Lego robot (lejos) and I put some code in setup that the robot needs to work. However, when I call it outside TinyVM (the VM that is installed on the robot), java crashes since it the VM hasn't been initialized properly (because the tests run on my PC). For unit-testing the setup isn't important.
I can't stub the classes/methods setup calls since some of them are public static final variables.
推薦答案
感謝您的建議,但它有點太復雜了.
我最終通過擴展類并覆蓋我的設(shè)置方法來模擬該方法.這樣默認構(gòu)造函數(shù)就不會調(diào)用它的 setup 實現(xiàn),而是調(diào)用被覆蓋的方法.
代碼如下:
Thanks for the suggestions, but it was a little bit too complex.
I ended up mocking the method by extending the class and overwriting my setup method. This way the default constructor won't call its implementation of setup, it will call the overwritten method instead.
Here is the code:
// src/author/MyClass.java
public class MyClass {
public MyClass() {
setup();
}
protected void setup() {
throw new Exception("I hate unit testing !");
}
public boolean doesItWork() {
return true;
}
}
// test/author/MyClass.java
public class MyClassTest {
private class MockedMyClass extends MyClass {
@Override
protected void setup() {
}
}
private MyClass instance;
@Before
public void setUp() { // Not to be confusing with `MyClass#setup()`!
instance = new MockedMyClass();
}
@Test
public void test_doesItWork() {
assertTrue(instance.doesItWork());
}
}
如果您不希望 MyTest 的 setup 方法被除您的測試之外的其他子類調(diào)用或覆蓋(因為其他開發(fā)人員可能會使用 setup 方法將事情搞砸),只需將可見性更改為默認值,并且只更改您的類將能夠調(diào)用設(shè)置.
If you don't want MyTest's setup method to do called or overwritten by other subclasses except your test (because other developer might mess things up very badly by using the setup method), just change the visibility to default and only your classes will be able to call setup.
如果有更簡單的方法,請回答問題,因為我對我的解決方案不是 100% 滿意.
If there is a simpler way, please answer the question because I'm not 100% content with my solution.
這篇關(guān)于Mockito Spy - 調(diào)用構(gòu)造函數(shù)之前的存根的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!