java - Enum-based singleton implementation and unit tests which preserve state as a side-effect of enum -


As many say, singleton is bad, it's an "anti-pattern". Fortunately or not, I work with some code which is in it and it will not work in the near future. So my problem is as follows.

A singleton state:

  Import java.util.HashMap; Import java.util.Map; Public Enum Singleton {INSTANCE; Private Last Maps & lt; String, string & gt; _mapper = New Hashmap & lt; String, string & gt; (); Public string getValue (string key) {return _mapper.get (key); } Public Zero addEntry (string key, string wall) {_mapper.put (key, val); } Remove the public string (string key) {return _mapper.remove (key); }}   

Very dumb test that does not take into account that the singleton INSTANCE state is preserved on the test run:

  import org. Junit.assert; Import org.junit.Test; Public category singlettest {public static final string KEY_1 = "key_1"; @Test Public Zero Teston () {Singleton. INSTANCE.adderer (KEY_1, "val_1"); Singleton INSTANCE.addentry ("key_2", "val_2"); } @Test Public Zero Test Two () {Assert.assertNull (singleton.INSTANCE.getValue (KEY_1)); }}   

How can the state be cleaned in the middle of the trial? Can this be done with the junket runner?

The actual position of the object is more complex and has been started through a constructor. I was looking for some sort of thing:

You have to execute @After each execution Will be executed after. In this method, you can clear the position of the map in your Inm:

 after  @ public clear () {singleton. INSTANCE.removeKey (KEY_1); Singleton.INSTANCE.removeKey ("key_2"); // and on and on ...}   

Of course, a better way in your enum would be a clear method that would map Will clear the values, so your @after method will decrease the body:

 after  @ public zero clear () {/ such method can create a singleton Are there. INSTANCE.clearEntries (); }    

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -