Home > database >  Call another method in Unit Test in same class
Call another method in Unit Test in same class

Time:09-17

We have a unit test that inside of this unit reference another method in my service. Should I call another method in current unit test or use mocking solution?

In my test case we call reference to method ChooseDoor() that do some operation and after that we call Act method SwitchDoor(), we should use some mocking or this approach is ok? Because reference method and act that we call, they are in the same class and don't have any dependency to other class.

public class GameService
{
 public Door ChoosesDoor()
 {
 //some logic
 }

 public Door SwitchDoor()
 {
 //some logic
 }
}


[Fact]
public void switch_door_should_return_a_new_door_with_a_valid_state_that_chooses()
{
 //Arrange
 var oldChoosesDoor =_game.ChoosesDoor();

 //Act
 var newDoor = _game.SwitchDoor();

 //Assert
 oldChoosesDoor.DoorState.ShouldBe(State.Stateless);
 newDoor.DoorState.ShouldBe(State.Chosen);
 oldChoosesDoor.DoorState.ShouldNotBe(newDoor.DoorState);
 oldChoosesDoor.Number.ShouldBeInRange(1,3);
}

CodePudding user response:

It is fine as long as you are e2e testing but, but for unit testing, by doing this you are forcing dependencies from one another. although you as a developer tend to reuse code as much as possible, for unit testing you would follow the AAA pattern mandatory.

CodePudding user response:

Calling other methods of the class under the test as part of setup is totally ok.
By doing this you will kinda test another method as well. Notice that you are testing a behaviour of your code.

Even in unit testing, unit is a unit of the behaviour, which can include single or multiple different methods or types.

"Test in isolation" means that tests should be isolated from other tests.

  • Related