# How to set and save a variable using the script

**URL:** <https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351>\
**Category:** Mobile Testing\
**Tags:** mobile-testing, katalon-studio\
**Created:** [October 21, 2021, 6:00am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351 "2021-10-21T06:00:41Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh.thompson](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/josh.thompson/32/16103_2.png) [@josh.thompson](https://forum.katalon.com/u/josh.thompson)\
**Post date:** [October 21, 2021, 6:00am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/1 "2021-10-21T06:00:42Z")

</div>

Hi there!

I’m running a test which generates me an ID. This ID increments by 1 every time the test is run. I need to verify this ID each time the test is run, but as it is a dynamic value I am struggling to do so.

I have thought of ways to do this but cannot **set AND save** a variable value.

For example, I need to be able to do this and **save** it each time so it will continuously work.

def init\_value = 2900  
def value = init\_value + 1  
init\_value = value

So I need to be able to **SAVE** the variable value at the end of every test execution. Essentially, how do I set the value of a variable using groovy and then save that variable value for further use.

I apologise for repeating myself, but just wanted to make the question as clear as possible.

Any help is greatly appreciated.

I want to save the variable value here

 ![Screen Shot 2021-10-21 at 4.03.41 pm](https://europe1.discourse-cdn.com/katalon/original/3X/6/5/65cefd44345a3450488ec89c3c30a551e58f0e31.png)

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [October 21, 2021, 8:22am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/2 "2021-10-21T08:22:37Z")

</div>

> [@josh.thompson](#):
>
> I want to save the variable value here

What do you mean by saying “here”? Where do you want to save the value into? Please state it clearly.

---

<div class="post-metadata">

**Author:** ![josh.thompson](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/josh.thompson/32/16103_2.png) [@josh.thompson](https://forum.katalon.com/u/josh.thompson)\
**Post date:** [October 21, 2021, 10:36pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/3 "2021-10-21T22:36:48Z")

</div>

I added a screenshot right below the “here.” I want it saved in the variables tab

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [October 21, 2021, 11:14pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/4 "2021-10-21T23:14:02Z")

</div>

Do you mean you want to increment the “Default value” of “variable” from 0 to 1 by script?

I have an idea how to implement it, but it is not a good approach.

However I would tell you the straight forward scenario how to. The content of Variable tab of a “New Test Case” is serialised into an XML file at the path of “`projectDir/Test Cases/New Test Case.tc`”, which looks like this:

```auto
<?xml version="1.0" encoding="UTF-8"?>
<TestCaseEntity>
   <description></description>
   <name>New Test Case</name>
   <tag></tag>
   <comment></comment>
   <testCaseGuid>c46d1117-79df-4d02-a44f-d6a0c03f43e0</testCaseGuid>
   <variable>
      <defaultValue>'bar'</defaultValue>
      <description></description>
      <id>d70ab867-638b-4043-a88c-2e4bc5168e19</id>
      <masked>false</masked>
      <name>foo</name>
   </variable>
</TestCaseEntity>

```

Here you can find an XML element

`<defaultValue>'bar'</defaultValue>`

This is the serialized format of a Default value of a variable `foo` of the Test Case.

You might be able to write a Test Case script to edit this XML file. I guess, Katalon Studio does not prohibit you from doing so.

Let me suppose you have developed that Test Case script. Every time you executed it and edited the XML file, **you have to close the project and reopen it**. This is to let Katalon Studio reload the edited XML file.

I do not think that this approach is good.

* * *

If you are capable of Groovy programming, you should be able to write a script that makes a text file in the project directory, and update it. The script will create a file, for example `projectDir/history.json`, with the initial state

```auto
{"times":0}

```

Once your test has run, the file should be updated to:

```auto
{"times":1}

```

Next time it should be updated to:

```auto
{"times":2}

```

and so on.

Your test case script needs to be capable of entirely managing (create/read/write/delete) the file. Skill of Groovy programming is required here.

I have no other idea easier to implement.

---

<div class="post-metadata">

**Author:** ![josh.thompson](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/josh.thompson/32/16103_2.png) [@josh.thompson](https://forum.katalon.com/u/josh.thompson)\
**Post date:** [October 21, 2021, 11:15pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/5 "2021-10-21T23:15:16Z")

</div>

Yes, on every run.

---

<div class="post-metadata">

**Author:** ![josh.thompson](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/josh.thompson/32/16103_2.png) [@josh.thompson](https://forum.katalon.com/u/josh.thompson)\
**Post date:** [October 22, 2021, 4:36am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/6 "2021-10-22T04:36:23Z")

</div>

Thanks for the reply … seems like a lot of work for such a small issue. Maybe this thread should be moved to feature requests.

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [October 22, 2021, 4:50am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/7 "2021-10-22T04:50:17Z")

</div>

> [@josh.thompson](#):
>
> seems like a lot of work for such a small issue.

I agree with you.

Katalon Studio does not provide user with any built-in means of storing current test results and retrieving the previous record.

@Russ_Thomas

Could you move this topic to the “Feature Request” category?

---

<div class="post-metadata">

**Author:** ![daniel.makra](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/daniel.makra/32/18397_2.png) [@daniel.makra](https://forum.katalon.com/u/daniel.makra)\
**Post date:** [October 22, 2021, 8:35am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/8 "2021-10-22T08:35:50Z")

</div>

I have a not-so-complex workaround for this. In my similar test case I read lines from a text file, save them into variables, modify some as needed and write back into the file.

The below example refers to a local txt which contains only a number in the first line.

You should think about the test case outcomes whether you want to save the incremented ID or not, if it fails at some point.

The downside of this FileWriter solution that it overwrites the whole text file, so if you have more than one line, you need to read all and write back all of them. including break lines.

```
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.io.FileWriter;
import java.io.IOException;

String filename = 'C:\\tmp\\var.txt'
ArrayList<String> lines = new ArrayList<>(Files.readAllLines(Paths.get(filename)));

String var1str = lines.get(0)
int var1int = var1str as int

var1int++

try {
    	FileWriter writer = new FileWriter(filename, false);
        writer.write(Integer.toString(var1int));
        writer.close();
} catch (IOException e) {
   	e.printStackTrace();
}
```

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [October 22, 2021, 9:08am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/9 "2021-10-22T09:08:25Z")

</div>

My sample Test Case:

```auto
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

final String fileName_ = "history.json"
final DateTimeFormatter formatter_ = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

Path projectDir = Paths.get(RunConfiguration.getProjectDir())
Path f = projectDir.resolve(fileName_)

def history = readHistory(f)

history["times"] += 1
history["lastRunAt"] = LocalDateTime.now().format(formatter_)

writeHistory(history, f)

WebUI.comment("history.times = ${history['times']}")

/**
 * 
 * @param f
 * @return
 */
def readHistory(Path f) {
	if (!Files.exists(f)) {
		Map m = ["times":0]
		f.text = JsonOutput.toJson(m)
	}
	return new JsonSlurper().parse(f.toFile())	
}

/**
 * 
 * @param history
 * @param f
 * @return
 */
def writeHistory(Object history, Path f) {
	f.text = JsonOutput.toJson(history)
}

```

This creates `history.json` file with the following content like this:

```auto
{"times":8,"lastRunAt":"2021-10-22 18:06:48"}

```

This will show the following at the 8th times of execution.

```auto
2021-10-22 18:06:48.731 INFO c.k.k.c.keyword.builtin.CommentKeyword - history.times = 8

```

You can extend the script and add more data items in the `history.json` file.

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [October 22, 2021, 1:54pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/10 "2021-10-22T13:54:26Z")

</div>

> [@kazurayam](#):
>
> Could you move this topic to the “Feature Request” category?

> [@New API to modify local files in a project](http://forum.katalon.com/t/new-api-to-modify-local-files-in-a-project/59389):
>
> @duyluong @ThanhTo @devalex88 This has come up a few times in various ways and for various reasons – but they all come down to the same basic requirement: Add a simple API to read/write values from/to a local file The file would support storage and retrieval of test case/suite values across time, between runs. I, personally, would favor a JSON file. But XML would work, too. In addition, if GlobalVariables and TC variables could be populated from a related API, drawing their values from the s…

---

<div class="post-metadata">

**Author:** ![chrisstu](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/chrisstu/32/18464_2.png) [@chrisstu](https://forum.katalon.com/u/chrisstu)\
**Post date:** [October 28, 2021, 11:53pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/11 "2021-10-28T23:53:27Z")

</div>

Hi Josh,

Could you clarify “need to verify this ID each time the test is run”, what the purpose of this verification? Or do you have other use cases?  
So I can suggest a better solution for the problem.

---

<div class="post-metadata">

**Author:** ![josh.thompson](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/josh.thompson/32/16103_2.png) [@josh.thompson](https://forum.katalon.com/u/josh.thompson)\
**Post date:** [November 1, 2021, 10:57pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/12 "2021-11-01T22:57:59Z")

</div>

Hi Chris,

I need to verify the ID is being sent in the correct order. So for example on the first run, I know the ID will be 2554. If I run the test again, I need to make sure the ID is now 2555.

Hope this helps.

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [November 2, 2021, 1:55pm UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/13 "2021-11-02T13:55:20Z")

</div>

> [@josh.thompson](#):
>
> I need to verify the ID is being sent in the correct order.

Could you explain what “the ID” is? What does it mean, what does it stand for? Who (which software component) decides the ID value? When is the ID value incremented? When is the ID value is initialised to 0? Is “the ID” value visible and accessible as a HTML element? If not, how your test script will get access to the value of “the ID” (by which Katalon Keyword)?

---

<div class="post-metadata">

**Author:** ![kazurayam](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/kazurayam/32/333_2.png) [@kazurayam](https://forum.katalon.com/u/kazurayam)\
**Post date:** [November 9, 2021, 3:32am UTC](https://forum.katalon.com/t/how-to-set-and-save-a-variable-using-the-script/59351/14 "2021-11-09T03:32:13Z")

</div>

> [@josh.thompson](#):
>
> So I need to be able to **SAVE** the variable value at the end of every test execution.

@josh.thompson

I guess you don’t need to save the variable value into the `history.json` at all _if the ID is incremented by a simple event, e.g, log-in/log-out the App_.

Your test case script should be able to make 2 or more times of firing the events (login/logout) in a single test case execution. Then your test case script would be able to check how the value of ID moves at each event firing. In this scenario, your test case will create a variable and update/read it, but it doesn’t have to save the value into an external file to pass to the following Test Case runs.

I am just guessing … You haven’t explained enough about the ID nature, so it is difficult for others to have clearer idea about your problem.
