Reputation: 5619
I have a class that I am writing a test for. I recognize this is a candidate for refactor and it has been added to the backlog. In the meantime I am looking for a quick solution to move forward.
The catch is that numerous methods in the class use the private variables. However they are null unless you call one specific method first. Yes it should not be coupled like this. However it is what it is for now.
My class is a service that looks like this:
import { Injectable } from "@angular/core";
@Injectable()
export class SortService {
constructor() { }
// Private Members
private allSort: Output[] = null;
private supportedSort: Output[] = null;
private allSortMap: Map<string, Output> = new Map<string, Output>();
checkSort(): Promise<void>
{ //Populate variables happens here along with other business logic }
//returns the list of all sort output device kinds
getSortOutput(name: string): Output {
return this.allSortMap.get(name);
}
}
Now if we want to write a test for getSortOutput then we have to call checkSort first but that is a very limited test as we can't throw various allSortMap values at getSortOutput to exercise it.
We did make the private into public and then we could exercise them thoroughly. So this does work but....
// Private Members
public allSort: Output[] = null;
public supportedSort: Output[] = null;
public allSortMap: Map<string, Output> = new Map<string, Output>();
The point of this question is can we mock and pass the private values. Something along the lines of this in our TestBed config or similiar?
providers: [SortService ,
{provide: Output, name:"allSort", useValue: mockAllSort},
{provide: Output, name:"supportedSort", useValue: mockSupportedSort},
{provide: Map<string, Output>, name:"allSortMap", useValue: mockAllSortMap}]
Upvotes: 2
Views: 3043
Reputation: 5619
As @R.Richards confirmed in his comment rock and a hard place. For now we have made the values public so we can test. This was acceptable to us as it will be refactored out of existence and does not compromise the application.
Upvotes: 1