我正在尝试监视一个对象,并且我想在构造函数调用它之前存根由构造函数调用的方法.
我的班级是这样的:
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() {
}
}
不得调用 setup 方法.那么,我如何监视这个方法(以及存根设置,使其什么都不做)?
它可以很好地模拟该方法,但我想对 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.
为什么需要存根设置方法以使其不执行任何操作:
我正在编写乐高机器人(lejos),并在设置中放置了一些机器人需要工作的代码.但是,当我在 TinyVM(安装在机器人上的 VM)之外调用它时,java 崩溃,因为它没有正确初始化 VM(因为测试在我的 PC 上运行).对于单元测试,设置并不重要.
我不能存根类/方法设置调用,因为其中一些是公共静态最终变量.
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.
感谢您的建议,但它有点太复杂了.
我最终通过扩展类并覆盖我的设置方法来模拟该方法.这样默认构造函数就不会调用它的 setup 实现,而是调用被覆盖的方法.
代码如下:
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 方法被除您的测试之外的其他子类调用或覆盖(因为其他开发人员可能会使用 setup 方法将事情搞砸),只需将可见性更改为默认值,并且只更改您的类将能够调用设置.
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.
这篇关于Mockito Spy - 调用构造函数之前的存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!