I have similar methods in the business layer. I am new to unit testing and sometimes get confused. For an idea, can you suggest, what will be a better approach to test this method
behaviour? I am using C# NUnit and Moq
public int? AddNewCatRetID(string categoryName)
{
int? categoryID = 0;
Adapter.AddNewBlogCategoryReturnID(categoryName, ref categoryID);
if (categoryID.HasValue)
return categoryID;
return 0;
}
where
Adapter = Visual Studio 2008, Data Set Designer generated TableAdater
AddDeveloperCategoryReturnID() = Name of a function which utilises a Stored procedure in DB
It adds a new record, “Category” and returns its auto generated ID. If it is non zero, we take that result for further processing.
I know should not be interested in talking to Database, below is the procedure, just to give an idea about what is going on in DB
PROCEDURE [dbo].[AddDeveloperCategoryReturnID]
@NAME NVARCHAR(MAX),
@CATEGORY_ID INT OUTPUT
AS
BEGIN
INSERT INTO [AllTimeGreatProgrammersDateBase].dbo.CATEGORIES(NAME )
VALUES (@NAME );
SET @CATEGORY_ID = SCOPE_IDENTITY();
SELECT @CATEGORY_ID;
END
some issues
- how to check the values returned using “ref” from the method
- what will you prefer to test and not to test? will be great if can list
I’d first convert
Adapter.AddNewBlogCategoryReturnID(categoryName, ref categoryID)so that instead of returning a variable by reference, it simply returned the value.Then, I would extract that into a virtual method.
To test
AddNewCatRetID, I would extend the class to make a testable version, and override that virtual method to return anint?stored in a public variable.That way, when you test to see what happens when you call
AddNewCatRetIDin a situation where there’s a 0 in the database, you don’t need to actually put a 0 in the database – you just set that parameter on the testable version of your class, and when your test callsAddNewCatRetID, instead if hitting the database, it just returns the value you set. Your test is guaranteed to be faster if you can avoid hitting the database, and since it’s MS’s generated adapter, there’s not really a need to test it – you only care about what your method does with what the adapter returns.