Configuration executes before Test But files copied after Test

Hi All,
I use Gradle 5.5.1, on java project.
I try to get the latest modified File(last 2) from a folder(“html-output”), using below script. The script runs fine and get the latest files, if I run this task independently, but when I run the same as a part of build script, It does not fetch the latest modified files.
Below script get the latest modified file from “html-output” folder before executing test, as a result, I get the previous run test results for the current test.

Copy task happens after the test and so the files are copied to test-output, i.e latest modified File is set before test and files are copied after test due to mustRunAfter.

Could someone help me on how to get the latest modified files after test run.

task copyReport(type: Copy, dependsOn: ‘copyResults’) {
mustRunAfter test
mustRunAfter copyGradleReport
//Get all .html files under html-output
def allHtmlFiles=
new File("${project.rootDir}/html-output").eachFileRecurse {
if (it.name =~ /.*.html/) {
allHtmlFiles << it
}
}
//sort all .html files under html-output by timestamp
def sortedHtmlFiles = allHtmlFiles.sort{ a,b -> b.lastModified() <=> a.lastModified() }
from file(sortedHtmlFiles[0])
into(file(“test-output/”))
from file(sortedHtmlFiles[1])
into(file(“test-output/”))
}

I was able to resolve by creating a separate task and add doLast.
Earlier I crated a copy task with doLast which failed. Now I created a task without type:copy and doLast now works.

task allReport {
mustRunAfter test
doLast {
def allHtmlFiles=
new File("${project.rootDir}/html-output").eachFileRecurse {
if (it.name =~ /.*.html/) {
allHtmlFiles << it
}
}
//sort all .html files under html-output by timestamp
def sortedHtmlFiles = allHtmlFiles.sort{ a,b -> b.lastModified() <=> a.lastModified() }

  copy {
  	from sortedHtmlFiles[0]
  	into "test-output/"
  }
  copy {
  	from sortedHtmlFiles[1]
  	into "test-output/"
  }
 }

}