Skip to content

Mocks and stubs: stubs

Dacian Roman edited this page Feb 17, 2022 · 3 revisions

Stubs

Stubs are Fakes which are not tracked. This means that you can execute your unit tests, using the fake methods; but Rooibos will not fail your tests if things were not as expected (i.e. wrong params, wrong number of invocations). These can be very handy for setting certain test conditions (i.e. you can create a fake network response that will return a speific result, which drives your test)

To create a stub, we use the Stub method:

function Stub(target, methodName, expectedInvocations = 1, expectedArgs = invalid, returnValue = invalid) as object
  • The target is the object which will have it's method replaced,
  • Method name is the name of the method to replace
  • expectedInvocations is the number of times we expect the method to be called
  • expectedArgs is an array of values we expect the method to be invoked with
  • returnValue is the value we wish to return
A simple example

Given a ViewModel, named DetailsVM, which has a method LoadDetails, as such:

function LoadDetails()
	isNetworkRequestExecuted = m.ExecuteNetRequest("http://my.data.com/get")
	m.isLoading = isNetworkRequestExecuted
	m.isShowingError = not isNetworkRequestExecuted
end function

We can use a stub, to facilitate testing against the network layer

detailsVM = CreateDetailsVM()
returnJson = {success:false}
m.Stub(detailsVM,"ExecuteNetRequest", invalid, returnJson)

detailsVM.LoadDetails()

m.assertFalse(detailsVM.isLoading)
m.assertTure(detailsVM.isShowingError)

In this case, our detailsVM object, will not actually call ExecuteNetRequests's source code; but will instead call a fake (i.e fake method body), which can return predtermined values, or be later checked for invocation arg conformance.