Reputation: 486
I'm new to unit tests, so please forgive me if this is a noob-question:
I'm trying to test a function:
<TestMethod>
Public Sub CheckSomethingTest()
Dim testObject as new MyClass()
Assert.IsTrue(testObject.CheckSomething(), "Check failed")
End Sub
The MyClass.CheckSomething function is accessing a global shared method which is making a database-query.
Public Function CheckSomething() as Boolean
Dim length as Integer = GlobalModule.GetLegthFromDb()
Return length > 0
End Function
Content of GlobalModule:
Public Class GlobalModule
Public Shared Function GetLegthFromDb() As Integer
'pretend database is not available
Throw New InstanceNotFoundException("DB Connetion not set")
End Function
End Class
As the database is not available for the test, I get a Nullpointer exception.
Is there any way to mock (or something else) the GetLegthFromDb method for the test?
Upvotes: 0
Views: 2654
Reputation: 486
After some additional research I found a solution that fits my requirements:
I used Microsoft Fakes for mocking the Shared Function.
<TestMethod>
Public Sub CheckSomethingTest()
Using s = Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()
MockTest.Fakes.ShimGlobalModule.GetLegthFromDb = Function() As Integer
Return 111
End Function
Dim testObject As New MyClassA
Assert.IsTrue(testObject.CheckSomething(), "Check failed")
End Using
End Sub
MockTest is the Namespace of my project.
Upvotes: 0
Reputation: 13399
GlobalModule
needs to be injectable in the class and when you instantiate the class you're trying to test, you can inject a mock of GlobalModule
in that class. It's also better to have it interfaced.
The code is in C# since it's easier for me, but you probably can translate it easily.
public class MyClass()
{
IGlobalModule _globalModule;
public MyClass (IGlobalModule globalModule)
{
_globalModule = globalModule; // use this in the method
}
public bool CheckSomething()
{
return _globalModule.GetLegthFromDb() > 0;
}
}
For the test:
var mock = new Mock<IGlobalModule>();
mock.SetUp(m=>m.GetLegthFromDb()).Returns(100);//whatever you want to return
var testObject = new MyClass(mock.Object);
Assert.IsTrue(testObject.CheckSomething(), "Check failed")
Upvotes: 1