Question

We have some existing static methods that are grouped in VB modules.

I want to introduce unit testing to the company, and am looking into using NUnit and NSubstitute.

I can't seem to create a Substitute for the VB module I want to test, or find any examples of how to do this. I am trying to do something like:

Dim Sub = Substitute.For(MyModule)()

but VB tells me 'MyModule is a type and cannot be used as an expression'.

If I try

Dim Sub = Substitute.For(Of MyModule)()

VB tells me 'Module 'MyModule' cannot be used as a type'.

Have I got the syntax wrong or am I trying to do something stupid?

Était-ce utile?

La solution

It is not appropriate to unit test Modules and Shared methods (static classes and methods in C#) with a mocking framework because:

  • Modules (static classes in C#) cannot:
    • inherit from base classes
    • implement interfaces
    • and thus, be mocked
  • Shared methods (static methods in C#) in mocked instances cannot be called

So, to unit test a Module or a class with Shared methods you need to do so directly. Example: (Unit test attributes omitted...)

Public Class A
    Public Shared Function Go(a As Integer) As Integer
        Return a + 10
    End Function
End Class

Public Class TestClass
    Public Sub Test()
        Assert.AreEqual(A.Go(5), 15)
    End Sub
End Class

Autres conseils

make sure your sending in an interface and I wouldn't use a variable name as Sub as it's a reserved type.

Example Dim fakeWebRequestService = Substitute.For(Of IWebRequestService)()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top