如何嘲笑私人内部阶级 [英] How to mock a private inner class

查看:90
本文介绍了如何嘲笑私人内部阶级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个spring应用程序,我想在像这样的控制器上创建一个整体测试.问题在于Wrapper类是私有内部类,因此测试中不了解Wrapper.是否可以在不更改控制器类的情况下使用Mockito对其进行模拟.我可以使用prepareData()获取该对象的实例,但是我不知道这是否可以用来模拟该对象.

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.

谢谢

@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);
    ....
}

推荐答案

您的测试是在方法上进行的,但它会测试整个类的行为.如果您的内部类是私有的,则其实现细节.测试不应该知道的东西.该内部类中有很多行为,您想独立对其进行测试,也许您应该将其公开并与此类分开.

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!

这篇关于如何嘲笑私人内部阶级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆