Unit testing accessors (getters and setters)

后端 未结 3 595
春和景丽
春和景丽 2020-12-30 21:52

Given the following methods:

public function setFoo($foo) {
    $this->_foo = $foo;
    return $this;
}

public function getFoo() {
    return $this->_         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 22:08

    This is a common question but strangely can't find a dupe on SO.

    You could write unit tests for accessors but the majority of practioners do not. i.e. if the accessors do not have any custom logic, I would not write unit tests to verify if field access works. Instead I would rely on the consumers of these accessors to ensure that the accessors work. e.g. If getFoo and setFoo don't work, the callers of these method should break. So by writing unit tests for the calling methods, the accessors get verified.

    This also means that code coverage should not be a problem. If you find accessors that are not covered after all test suites are run, maybe they are redundant / unused. Delete them.

    Try to write a test that illustrates a scenario where a client will use that accessor. e.g. The below snippet shows how the Tooltip (property) for the Pause Button toggles based on its current mode.

    [Test]
    public void UpdatesTogglePauseTooltipBasedOnState()
    {
        Assert.That(_mainViewModel.TogglePauseTooltip, Is.EqualTo(Strings.Main_PauseAllBeacons));
    
        _mainViewModel.TogglePauseCommand.Execute(null);
        Assert.That(_mainViewModel.TogglePauseTooltip, Is.EqualTo(Strings.Main_ResumeAllBeacons));
    
        _mainViewModel.TogglePauseCommand.Execute(null);
        Assert.That(_mainViewModel.TogglePauseTooltip, Is.EqualTo(Strings.Main_PauseAllBeacons));
    }
    

提交回复
热议问题