lundi 27 juillet 2020

Mockito Simplifying My (Sorta Complicated)Tests

I am basically trying to create a file where there are two ways a test can pass throughout the file. The catch is that both requirements will be fulfilled in every test except for one. It's hard to explain, so I'll try to show you. (This is a pretty simplified version of what I have, and I wrote it offhand quickly, so I'm sorry for errors)

public class Foo(){
private double number;

public Foo(double number){
this.number = number;
}

  Double myMethod(double number){
number = 10;
return number;
}
}
public class Bar(){
private double number;

public Bar(double number){
this.number = number;
}
  Double myMethod(double number){
number = 20;
return number;
}
}

and then the test would be like

public class test(){
  public void test1(){
try{
assertEquals(10, Foo.myMethod(placeholder));
} catch(AssertionError e){
assertEquals(20, Bar.myMethod(placeholder));
}

and then what I want to do is use whether or not the number is 10 or 20 in my other tests. So like

public void test2(){
if(number == 10){
// whatever test code
} else {
// other test code
}

I have tried setting a boolean in the first test. For some reason, the boolean just defaults to being true in later tests. So I added print statements. I realized the tests are not run in order. I added an annotation to the top of my file to run the tests in the order I want and verified it with print statements.

I'm also almost positive it's impossible to make a test return something. It seems they always have to be void.

The last thing I tried was writing a method that dependency injects the boolean variable. So, a test runs, sets a variable to t/f, and then the method injects that value and returns it. Then I use that method in my test, but that does the same thing (assumes boolean is true).

What I've been doing (which works.. but ew) is basically copy/pasting the first test as a try/catch into each subsequent test. Ugh. I hate it. It does work. But it's so nasty. Here's what it looks like (ish):


public void test2(){
try{
assertEquals(state1, Foo.number);
//insert test code
} catch(AssertionError e){
assertEquals(state2, Bar.myObj);
//insert test code
}
}

To clarify, the verifier that I have is not just one line of code (it's not assertEquals). It is four lines, and I'm fairly certain that's as small as I can get it. So either I have to paste four lines of code in each test twice, or some smart person online can help me!

I'm sorry for the long post I'm not good at these.

Aucun commentaire:

Enregistrer un commentaire