Unit-Testing delegating methods

夙愿已清 提交于 2019-12-23 14:40:42

问题


Is there any point in Unit-Testing a method that the only thing it does is delegate work on another object? Example:

class abc {

    ...

    public void MoveLeft()
    {
        fallingPiece.MoveLeft();
    }

    ...
}

I am doing Unit-Tests for some existing classes I have, for learning purposes. It seems kinda odd to do a Unit-Test for this MoveLeft() method, for example. But I am unsure how would it have been had I done Test-First.

Thanks


回答1:


Will your code break if I do this ? If it would, then you need a test to catch it.

class abc {
    ...
    public void MoveLeft()
    {
        // fallingPiece.MoveLeft();
    }
    ...
}

Assumptions: abc is a public / exposed type and fallingPiece is a dependency. If this holds, then you need a test to test the MoveLeft behavior. If it isn't a public type, then you need a test for the public type XYZ that uses abc as a colloborator/dependency. You don't directly test it but it still needs to be tested.




回答2:


My understanding of unit tests is that they are there to ensure that the logic inside a method stays the same when you didn't intend for it to change, and this method has no logic in it. We have a lot of pass-through methods like that in the code base where I work. Ostensibly, they're "Controller" classes, but in most cases all they do is pass through to the data layer.

Yes, you can unit test them, assuming you have a way to mock fallingPiece. If you actually plan on expanding the MoveLeft method to include logic, it's probably a good idea.

However, to my comment above, it's probably a better move to just inline the method until you actually need to introduce logic around moving left.




回答3:


One case that this method can fail is when fallingPiece is null when Abc.MoveLeft gets called. Having a test case that builds a legitimate abc and calls abc.MoveLeft might be good idea. something like CanMoveLeft() { Abc abc =new Abc(); abc.MoveLeft(); Assert.That( abc.fallingPice has moved to left) }



来源:https://stackoverflow.com/questions/3474057/unit-testing-delegating-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!