java 如何模拟私有内部类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5593201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock a private inner class
提问by Javi
I have a spring application and I want to create a unitary test on a controller like this one. The problem is that the Wrapper class is a private inner class, so Wrapper is not understood in the test. Is it possible to mock it with Mockito without changing the controller class. I can use prepareData() to get an instance of the object, but I don't know if this could be used to mock that object.
我有一个 spring 应用程序,我想在这样的控制器上创建一个单一的测试。问题是Wrapper类是私有内部类,所以测试中没有理解Wrapper。是否可以在不更改控制器类的情况下使用 Mockito 模拟它。我可以使用 prepareData() 来获取对象的实例,但我不知道这是否可以用来模拟该对象。
Thanks
谢谢
@Controller
public class Controller {
private class Wrapper {
private Object1 field1;
private Object2 field2;
private Object1 method1(){
...
}
private Object2 method1(){
...
}
}
@ModelAttribute("data")
public Wrapper prepareData() {
return new Wrapper ();
}
public String save(@ModelAttribute("data") Wrapper wrapper, BindingResult result, Model model){
...
}
}
So in my test I would have something like this
所以在我的测试中我会有这样的事情
@Test
public void usernameEmpty(){
BindingResult result = Mockito.mock(BindingResult.class);
Model model = Mockito.mock(Model.class);
Wrapper data = //how to mock it
when(data.method1()).then(new Foo1());
when(data.method2()).then(new Foo2());
String returned = controller.save(data, result, model);
....
}
回答by helios
Your test is on methods, but it tests the whole class behavior. If your inner class is private then its an implementation detail. Something that the test shouldn't know. It there's a lot of behaviour in that inner-class and you want to test it independently maybe you should make it public and separate from this class.
您的测试是针对方法的,但它会测试整个类的行为。如果您的内部类是私有的,那么它就是一个实现细节。测试不应该知道的东西。该内部类中有很多行为,您想独立测试它,也许您应该将其公开并与此类分开。
Maybe you think: but then... it's a lot of code to test (a very big indivisible thing), can't I test something smaller? Well... yes. Test Driven Development mandates to make a minimal implementation and add more code only if you add more tests. So you start with some test and minimal implementation and evolve both of them until the tests have all the specification and the code all the implementation.
也许你会想:但是……要测试的代码很多(一个非常大的不可分割的东西),我不能测试更小的东西吗?嗯,是。测试驱动开发要求进行最少的实现,并且只有在添加更多测试时才添加更多代码。所以你从一些测试和最小的实现开始,然后发展它们,直到测试有所有的规范和代码所有的实现。
So don't worry about private inner classes. Test your class contract!
所以不用担心私有内部类。测试你的班级合同!