jeudi 1 janvier 2015

How to check private state in unit testing?

I have read some discussions on the internet. They say that we should not unit test private methods or check private state because that's implementation detail and a sign of bad design. But in my case, I really don't know how to do better.


Here is an example code (my actual code is angular using factory, but I try to create a same case using plain js so that everyone is easier to understand because the same cause is closure):



function closure(){
var state = {};

return {
refreshState : function(property1,property2) {
state.property1 = property1;
state.property2 = property2;

//store these properties into localstorage
},
getState: function () {
if (!state.property1) {
state.property1 = //retrieve from localstorage
}
if (!state.property2) {
state.property2 = //retrieve from localstorage
}
return state;
}
};
};

var objectToTest = closure();


In my real app, I can inject and mock the local storage, but it's a question here. My question is how to test that the refreshState method sets its private state because I cannot verify its value:



state.property1 = property1;
state.property2 = property2;


I'm thinking about stubbing the local storage and use the getState method to get the state. But it looks like integration test because the getState has its own logic that I cannot get rid of.


Aucun commentaire:

Enregistrer un commentaire