Le logger de la mort

Parfois, au cours d'une mission chez un client, on tombe sur du code pas testé, et pas toujours prévu pour être testé non plus. Je vais présenter un cas sur lequel je suis tombé récemment, issu d'un assez gros projet Java EE en cours de développement.

Une classe de services X effectue une certain nombre de traitements. En cas d'erreur, au lieu de jeter une exception métier, un code d'erreur est loggué. Impossible d'utiliser un @Test(expected=...), donc. Fort heureusement, le champ logger dans X est une interface, potentiellement mockable :
interface Ilogger {
  public abstract void logError(final Key key, final Object... messages);
  // blabla
}
Dans tous les cas où nous sommes intéressés, la méthode logError est appelée avec un paramètre Key représentant le code d'erreur. Malheureusement, le logger n'est pas injecté dans un setter, et il est privé. On aimerait tout de même vérifier que l'erreur est bien logguée sous certaines conditions. Solution, un peu de réflexion pour forcer le champ logger à une instance que l'on contrôle :
public class MockLogger implements ILogger {
  private List<Key> loggedKeys;

  public MockLogger() {
    super();
    loggedKeys = new ArrayList<Key>();
  }

  public void logError(Key key, Object... messages) {
    loggedKeys.add(key);
  }

  public boolean wasLogged(Key key) {
    return loggedKeys.contains(key);
  }

  public void resetLogCalls() {
    loggedKeys.clear();
  }
}
La méthode resetLogCalls permet d'utiliser la même instance du logger sur plusieurs tests, il faut l'appeler dans une méthode annotée @After. Il faut maintenant injecter notre propre logger dans le service testé :
Field f = serviceUnderTest.getClass().getDeclaredField("logger");
f.setAccessible(true);
f.set(serviceUnderTest, myLoggerInstance);
f.setAccessible(false);
Et voila, nous pouvons maintenant faire des assertTrue utilisant la méthode wasLogged et la Key nous intéressant ! Notez l'appel à Field#setAccessible(boolean) pour contourner le caractère private du champ logger (que l'on restaure par la suite). Note : si le logger n'avait pas utilisé d'interface, nous aurions pu nous en sortir en créant une classe fille redéfinissant toutes les méthodes sans appels à super().

Commentaires

Par CHAUFFEUR PRIVE NICE le samedi 23 avril 2016 à 19:00

Hi outstanding blog! Does running a blokg similar to this twke
a gresat deal of work? I've absolutely no expertise in coding however I had
been hoping to start my own blog in the near future.
Anyways, should you have any recommendations or tips forr new blog owners please
share. I understand this is off topic nevertheless I simply wanted to ask.
Kudos!

Par which vpn for soccer le mercredi 12 décembre 2018 à 18:43

This web site truly has all of the information and facts I needed concerning
this subject and didn't know who to ask.

Par how good is express vpn le dimanche 16 décembre 2018 à 17:08

I'm impressed, I must say. Rarely do I come across a blog that's both equally educative and amusing,
and let me tell you, you've hit the nail on the head. The problem is something
which too few folks are speaking intelligently about. I'm
very happy I stumbled across this during my hunt for
something regarding this.

Par https://www.novaworlds.com.vn/ le mercredi 23 décembre 2020 à 03:12

Thanks designed for sharing such a pleasant idea, paragraph is
fastidious, thats why i have read it entirely

Par website le mardi 16 f´vrier 2021 à 15:48

I am regular visitor, how are you everybody? This paragraph posted
at this site is actually nice.

Par mobile phone parts le mardi 23 mars 2021 à 01:12

It's an amazing paragraph in support of all the internet visitors; they
will get advantage from it I am sure.

Par slot true wallet ไม่มี ขั้น ต่ํา le mercredi 10 novembre 2021 à 22:13

Just keep clicking and this handset with its mind -boggling options of
Geo-tagging, touch focus, face and smile
detection and picture stabilization will take care of all these minutes that makes your click the perfect one.

Orange offers a 24 -month contract deal with this handset.

This deal affords more flexibility and is there fore frequent amongst students
who're unwilling to enter into contract and want
extra freedom by way of their phone expenditure.
Aside from all this, the mobile phone also packs an 8
megapixels camera with, autofocus, twin-LED flash,Geo-tagging,
touch-focus, image stabilization and face detection so that users can having fun with taking
pictures crisp and clear images and videos both in day and evening.
With the time going by, R4 DS card change into increasingly
more important for the Nintendo DS customers because of its highly effective functions.
Which means this Toshiba mini laptop computer offers you far more battery
life when you are away from an electrical outlet.

Par พนันออนไลน์ ฟรี le samedi 27 novembre 2021 à 22:16

This page definitely has all the information and facts I needed
about this subject and didn't know who to ask.

Par พนันออนไลน์ ฟรี le samedi 27 novembre 2021 à 23:36

Appreciate this post. Will try it out.

Par Available Here le jeudi 03 mars 2022 à 08:54

Very good article. I certainly love this site. Keep writing!

Fil des commentaires de cet article

Ecrire un commentaire




Quelle est la première lettre du mot bqnd ? :