Cómo establecer variables de entorno globales cuando las pruebas unitarias

iamjoshua:

Estoy tratando de crear una unidad de prueba, sin embargo, cada vez que lo ejecuto me encuentro con nulllos valores de mis variables. La depuración de los puntos de emisión a mis variables de entorno no se utiliza en todo el mundo en mi unidad de prueba. Como classestoy probando llamadas de otra clase que a continuación hace referencia a sus valores de una variable de entorno. ¿Cómo hago uso de variables de entorno globales en IntelliJ ?.

Ya he añadido variables de entorno en la configuración de prueba como esta,

Sin embargo, esto no parece ser utilizado en todo el proyecto. Por lo tanto las clases de llamar a este variables de entorno están regresando nula. ¿Cómo hago que mi prueba de unidad y las clases que llama a utilizar las variables de entorno declaradas a nivel mundial ?. TIA. A continuación se muestra un fragmento de mi código de cómo mis variables de entorno están siendo utilizados en una clase

@Value("${fintech.clientid}")
private String clientId;
@Value("${fintech.secret}")
private String clientSecret;
@Value("${digifi-host}")
private String fintechHost;
@Value("${fintech-digifi-login-endpoint}")
private String loginUrl;
@Value("${fintech-single-session-endpoint}")
private String singleSessionUrl;

Lo que esto hace es de la clase, se llama a los valores almacenados en mi archivo application.properties. Y a partir del archivo application.properties, se trata de buscar los valores adecuados en las variables de entorno declarados en tiempo de ejecución.

So from Java Class > application.properties file/config > Runtime Environment Variables 

A continuación se muestra la pantalla de variables con valores nulos cuando la depuración de la prueba. Como se puede ver, todos los valores son nulos lo que significa que no se ha cargado las variables de entorno he puesto en la prueba unitaria. Por otro caso de prueba donde tenía un arreglo temporal (como puse en la respuesta aquí), que están pobladas y por lo tanto la carga de las variables de entorno correctamente, pero en mis muchos otros casos de prueba como ésta, no es así.

introducir descripción de la imagen aquí

PS: I've already found related articles in stackoverflow, but they are all test-class specific and that uses surefire plugins or setting the environment variables or via pom, but I don't need it to be there as it is a requirement for us to use environment variables on runtime as the values of the variables should be hidden and not visible on the code. I just simply need the entire project to use a global environment variable when it is doing its Unit Test. Much like how my project would use the environment variables I set in the IDE in normal runtime.

Just for Reference. I already did the ff.:


A.

@ClassRule
public final static EnvironmentVariables environmentVariables = new EnvironmentVariables().set("property1", "value1");

B.

@ContextConfiguration(locations = "classpath:application.properties")
public class LoginServiceTest {
...
}

C.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>  
      <environmentVariables>
        <SERVER_PORT>8082</SERVER_PORT>
      </environmentVariables>
    </configuration>
</plugin>

D.

@TestPropertySource(properties = {"property1=value1","property2=value2",})
public class LoginServiceTest {
...
}

E.

public class LoginServiceTest {    
static{
      System.setProperty("property1", "value1");
      System.setProperty("property2", "value2");            
...
}
iamjoshua :

UPDATE:

This solution worked on all of my test. You can refer here for more details.

@RunWith(SpringRunner.class)  //Add this
@SpringBootTest(classes = Application.class)   //Add this
public class LoginServiceTest {
...
}

Then on Run > Edit Configurations > Templates (in sidemenu) > JUnit introducir descripción de la imagen aquí

introducir descripción de la imagen aquí

  1. Then put all your environment variables here.
  2. Click + on the Upper Left window & Apply.
  3. Then delete all existing Unit Test command in your configuration and proceed to re-running all your test again plainly.
  4. Then you'll see the environment variables being added automatically on all your new and upcoming unit test.

    You won't have to manually add an environment variables to each unit test command alright as what I happen to do annoying before. Should you ever have an update on your environment variables. Delete the main unit test configuration you need to have an update, and update the JUnit Template instead so that changes will reflect to new unit tests that you may have.

PS:

Thing is, I still encountered the very same issue on some of my Unit Test, that even though the environment variables are being read properly on runtime and in some unit test alright with the above configurations. It is only during the other many Unit Test the very same environment variables are not being retrieved or received properly by the classes. At first I thought my classes are not really getting the proper environment variables and there must be something wrong as to how I stored the environment variables in IntelliJ, which it did not really, but it turns out this code format I have is the issue.

@Value("${fintech.clientid}")
private String clientId;
@Value("${fintech.secret}")
private String clientSecret;
@Value("${digifi-host}")
private String digifiHost;

It turns out,even though though this particular code works on runtime, it wont on Unit Test time, like ever.

De ahí que vanamente con este los códigos particulares hasta que ya era capaz de obtener las variables de entorno adecuadas en prueba unitaria. Se refieren a los cambios en el código anterior a la que se ha solucionado el problema para mí más adelante.

@Value("${fintech.clientid}")
public void getClientId(String tempClientId) {
    clientId = tempClientId;
}
private  String clientId;

@Value("${fintech.secret}")
public void getClientSecret(String tempClientSecret) {
    clientSecret=tempClientSecret;
}
private  String clientSecret;

@Value("${digifi-host}")
public void getDigifiHost(String tempDigifiHost) {
    digifiHost=tempDigifiHost;
}
private  String digifiHost;

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=402447&siteId=1
Recomendado
Clasificación