Reputation: 19
So , i have the following code structure
public void method1(int index)
{
switch(index)
{
case 1:
Method2();break;
case 2:
Method3();break;
}
}
public void Method2()
{
var entity = new SomeEntity();
repo.Add(entity);
var anotherEntity= new AnotherEntity();
repo.Update(anotherEntity);
}
While covering method2 with unit test, i ran into issue, that if i want to check that entity add to db, anyway it runs an update method too. How i can split it somehow, just wanna get maybe some best practices for method in which it's needed to do multiple operations with db. Thanks for helping me!
Upvotes: 0
Views: 764
Reputation: 32445
In tests you need to test only behaviour of the object.
In your case behaviour of your object is adding one entity and update another.
Object have public method Method2
which responsible for this behaviour.
So you ending up with two tests, one for updating and one for adding.
You can mock a repository and tests that methods Add
and Update
called with expected arguments. Or will be better if you can use "InMemory" database and have tests which cover persistence layer as well.
It is ok that Update
executed also in test for Add
, you will assert only behaviour of Add
and ignore Update
method.
Your problem have nothing to do with Single Responsibility Principle. Single Responsibility Principle means that object should have only one reason to change.
In your case if updating another entity is part of logic for adding another one - it should stay in one class/method and been tested as whole.
Upvotes: 3
Reputation: 66
First of all Method2() violates the single responsibility principle of SOLID
Single Responsibility Principle: a class should have only a single responsibility (i.e. changes to only one part of the software's specification should be able to affect the specification of the class).
These operations need to be in their own methods and in doing so will lead to:
Better options for writing unit tests.
public void Method2()
{
//This method only adds new entities
var entity = new SomeEntity();
repo.Add(entity);
}
public void Method3()
{
//This method only updates entities
var anotherEntity= new AnotherEntity();
repo.Update(anotherEntity);
}
Upvotes: 1