Pregunta

I have two tests they are exactly the same... barring two things, they call two separate service calls.. hence when im using mockito i have two seperate expectation and verify lines...

this is what i have done:

@test
TestA {
   baseTest("player");
}

@test
TestB {
  baseTest("member");

}

BaseTest(type type) {
  ....
  .....
  if type(player) {
    Mockito.when(player service call)
  }
  else {
    Mockito.when(member service call)
  }

  // make the call in code

  //verify

  if(player) {
     verify player specific service call...
  }
  else {

  }
}

I think the above is a test smell... just doesnt feel right...

Is there a better way then placing an If statement in my baste test?

¿Fue útil?

Solución

You should develope your test code independenly and join things when they have sense.

By example. One rule of thumb for initialization code (the first A of Arrange/Act/Assert) is that:

  1. you should write all the Arrange part of a test method in the test.
  2. if your method shares initialization with all the other methods, then put it in a @Setup method
  3. if some test method doesn't share that initialization it's probably because it doesn't fit in that test case.

So my conclusion is:

  1. write independent tests
  2. if they share things you can refactor
  3. but not too much (or in a weird thing like "if"s)!!! Adds complexity, not reuse.

In fact @artbristol answer makes sense: if you are using if's for alternate behaviour consider polymorphism. It's just I'm not sure until which point it's complex for test or not (probable it makes sense if the code is testing a similar class hierarchy).

Otros consejos

Anywhere you see repeated if statements like that, you can use polymorphism. You should make the "player service call" and "member service call" methods abstract in the superclass BaseTestSuper, which will also own the existing BaseTest method..

I would still just implement the 2 test classes separately. Code length and duplication don't really matter for tests, code readability, thoroughness and correctness take priority. In that light, just implement the 2 test cases separately.

In general you should not add any complexity to your tests. First, you can make mistake there (even in simple ifs). Second, your tests are not a documentation anymore, meaning that you can not easily understand what is the scenario of usage and behaviour of the tested class.

So it is a smell. :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top