Suppose we are as follows:CodeHttpcontext. Current. cache is called.
Public class cachemanager {public static httpcontext mhttpcontext = httpcontext. Current; Public void setcache
(String key, T value) {mhttpcontext. cache. insert (Key, value, null, datetime. maxvalue, new timespan (0,100, 0);} public t getcache
(String key) {return (t) mhttpcontext. cache. Get (key );}}
Now I have a class that calls the above getcache <t>
Public class languagecontroller {private cachemanager cachemanger = new cachemanager (); Public String get_userlanguage () {string userlanguage = cachemanger. getcache
("Userlanguage"); If (! String. isnullorempty (userlanguage) return userlanguage; Return "ZH-CN ";}}
Now we need to test the get_userlanuage of languagecontroller and write the following code:
[Testmethod] public void test_get_userlanguage () {cachemanager cachemanger = new cachemanager (); cachemanger. setcache
("Userlanguage", "En-GB"); languagecontroller = new languagecontroller (); Assert. areequal (languagecontroller. get_userlanguage (), "En-GB ");}
Run the test and fail. The following message is displayed.
System. nullreferenceexception: object reference not set to an instance of an object.
Tracking and debugging, the following method is found: mhttpcontext. cache is empty
Public void setcache
(String key, T value) {mhttpcontext. cache. insert (Key, value, null, datetime. maxvalue, new timespan (0,100, 0 ));}
Now, change the test code to the following:
[Testmethod] public void test_get_language_by_fake () {httpcontext. current = new httpcontext (New httprequest (null, "http: // 10.10.50.127/rgv2/devtest1", null), new httpresponse (null); cachemanager. mhttpcontext = httpcontext. current; cachemanager cachemanger = new cachemanager (); cachemanger. setcache
("Userlanguage", "En-GB"); languagecontroller = new languagecontroller (); Assert. areequal (languagecontroller. get_userlanguage (), "En-GB ");}
Test passed:
To sum up, when we test the code that contains httpcontext. Current. cache:
1. Publish httpcontext. Current. cache as the static attribute of the class. In this way, when the test is performed, all the changes are made.
2. Use the following code to assign values to httpcontext. Current.
Httpcontext. current = new httpcontext (New httprequest (null, "http: // 10.10.50.127/rgv2/devtest1", null), new httpresponse (null); cachemanager. mhttpcontext = httpcontext. current;
3. we recommend that you publish the values obtained by calling httpcontext as attributes to facilitate testing. For example, we will assign values directly to the following code. This is not relevant to this article, but it is just a practice.
Public class configcontroller {private string tempconfigpath; Public String mconfigpath {get {If (tempconfigpath = NULL) {tempconfigpath = httpcontext. Current. server. mappath (@"~ /App_data/config. xml ");} return tempconfigpath;} set {tempconfigpath = value ;}}}
4. We can also use mock, but I personally think the above method is simpler.