Accessing instance in testbox unit test

In my coldbox app, I have a model user that is using an internal validation construct:

this.constraints = {}

I want to be able to test this in the unit test for the User model.
According to the documentation there is BaseTestCase which has a getInstance() function, and a BaseModelTest which inherits those functions.

I have tried a number of things in my test class.
Setting a property with an inject for “ValidationManager@cbvalidation” or “provider:ValidationManager@cbvalidation”.

calling getInstance(“ValidationManager@cbvalidation”).

I get this error:

Global Bundle Exception (1 ms)

The function [getWireBox] does not exist in the String.

853: injector854: ){855: return getController().getWireBox().getInstance( argumentCollection = arguments );856: }857:

What version of ColdBox, and where are you calling getInstance()?

On ColdBox 6.x, you’ll need to set this.loadColdBox = true, make sure you aren’t blocking the default beforeAll() parent method, and run getInstance() inside your test, after you’re sure ColdBox has been loaded.

I believe ColdBox isn’t loaded by default on a model test, since that is a unit test and not an integration test.

Something like this:

component extends="path.to.coldbox.BaseModelTest" model="path.to.myModel" {
  // ensure coldbox loads during the parent beforeAll().
  this.loadColdBox = true;
  function beforeAll(){
    super.beforeAll();
    
    // coldbox is now loaded, and we can retrieve models via wirebox:
    variables.otherTestInstance = getInstance( "Foo@myApp" );
  }
}

If you want to use injections inside your test, do getWirebox().autowire( this ) inside the beforeAll() after the super.beforeAll() call.

Hope that helps. :slight_smile:

My version is 6.8.1+5.
This worked perfectly for me but required the:

getWirebox().autowire( this )

1 Like

I think if you peruse the test harness, or ask the coldbox CLI to create an integration test for you, you will see that an integration test does this by default.

I think. :slight_smile:

Yes, I saw that and there is a good argument as to whether this is a Unit or Integration test since I am testing the interaction between two components my model class and cbValidation.

But what I am testing here really is the constraints structure and the UDF function that I am using inside of that, which to me belongs here in the model unit test.

Thank you

1 Like