Reputation: 12799
I´m new on unit testing. I am developing a MVC project with a Service Layer where I do all business logic and access to database (through repository pattern)
I create a project to unit test my business logic, like that:
Service layer example logic I want to test:
public static bool HasPermissionToSomething(MyDomain domain)
{
if((domain.prop1 == true || domain.prop3 == false) && domain.prop2 == false)
return true;
return false;
}
So I created a unit test like that (using XUnit)
[Fact]
public void HasPermissionToSomethingTest()
{
var domain = MockDomain();
var hasPermission = MyService.HasPermissionToSomething(domain);
Assert.Equal(hasPermission, true);
}
Is that a good approach to test my service layer? Is my test a good one?
Thanks
Upvotes: 1
Views: 617
Reputation: 7484
You are heading in the right direction. You need to enhance the unit test a bit so that it declares more of what it is testing.
[Fact]
public void HasPermissionToSomethingTest()
{
var domain = MockDomain {prop1 = true, prop2 = true, prop3=true};
var hasPermission = MyService.HasPermissionToSomething(domain);
Assert.Equal(hasPermission, true);
}
And, you need more unit tests to cover the various conditions that trigger the true or false return. For this test, Xunit's theory will help so that you don't need quite so many tests.
[Theory, InlineData(true, true, true), InlineData(true, true, false)]
public void ShouldGrantPermission(bool prop1, bool prop2, bool prop3)
{
var domain = MockDomain {prop1 = prop1, prop2 = prop2, prop3 = prop3};
var hasPermission = MyService.HasPermissionToSomething(domain);
Assert.Equal(hasPermission, true);
}
Upvotes: 1