How to get resource in tests using Gradle? - testing

I have:
--src
-----main
-----test
--------resources
-------------test.zip
In test directory I have Spock test. How can I refer the test.zip file so to pass its absolute path to the test and to check some of my methods? I tried with new File('.').absolutePath but I want to find better solution
def "check checkTypeZipMethod"() {
expect:
assert testedMethod(new File('.').absolutePath+"test/resources/test.zip")==true
}

You can either try to locate the zip file based on ClassLoader#getResource, or configure the test task to set a system property pointing to the zip file. The latter is easier to implement, but harder to make work in environments other than Gradle (e.g. when running the test inside an IDE).
PS: In a Spock expect: or then: block, you can (and should) omit the assert keyword.

Related

cucumber - "Test ignored" error while running Runner in IntelliJ

I am trying to run a simple example of cucumber-Junit in Intellij, but not geting error "Test ignored". (I have installed cucumber for Java plugin)
My feature file, Runner class, Stepdefinition class and java class look as below:
I also tried to restructure the stepdefinition and feature file in multiple ways but it did not help.
1) Does the error mean, it is not finding stepdefinition file (Feature1Steps.java) ? if yes, how do I make it find it ?
2) I am not able to run feature file (Feature1.feature) either. It says : "Test Framework quit unexpectedly"
3) I have tried 1) and 2) with both the latest Cucumber for Java plugin and an older one (183.4284.148). But that did not solve the issue.
Could someone please help me here ?
Well, I did change multiple things and would like to post it here..
1) The words in scenario in feature file and step definition file are case sensitive so I corrected it. (in feature file when I write "Given that I have a Calculator", then in step definition file also I should write ( #Given("^that I have a Calculator$")). Earlier I had small c (calculator) in first step of my step definition file.
2) I just put stepdefinition file and Runnerclass files in the same package and feature file in resources folder. see screenshot below:
After having this structure I do not require to specify glue at all in Cucumber options in Runner class. I just require to specify where my feature file exists. see below:
3) now I am using cucumber version 4.2.0. But that did not make any difference I think.
I hope this helps others.
Move the .feature file to resources/com/example.
From the Cucumber docs:
"If Cucumber is telling you that your steps are undefined, when you have defined step definitions, this means that Cucumber cannot find your step definitions. You’ll need to make sure to specify the path to your step definitions (glue path) correctly.
By default Cucumber-JVM will search in the package (or sub-packages) of the runner class. You can also tell Cucumber-JVM explicitly which packages (and sub-packages) to search, with:
#CucumberOptions(glue = {"<package>", "<package>", "<etc>"})
public class RunCucumberTest{}"
"
(Sidenote: you are using a very old version of Cucumber. v5 is about to be released.)

How to send result file after all tests run in nunit console c#

Is there a way to send a mail with result file (I set this file in console command with option --result) after running.
I have run my selenium test cases in following way
How to Schedule Selenium Web Drivers Tests in C#
The result file was created after OneTimeTearDown function.
If sending an e-mail into OneTimeTearDown function - the result file comes incomplete
Thanks in advance
Sangeetha P.
I'm not sure I'd actually recommend doing this - but I think it's possible. Personally, I'd instead handle the email sending outside of the NUnit console, in a separate script in your CI System.
Anyway. You could achieve this by writing your own ResultWriter extension. Take a look at the implementation of the standard NUnit3XmlResultWriter as an idea - you'd essentially want the same thing, except to send the file by email, rather than write a file. (You may even want to make your ResultWriter actually inherit the NUnit3XmlResultWriter class.)

GO Unit testing structured REST API projects

I am trying to write nice unit tests for my already created REST API. I have this simple structure:
ROOT/
config/
handlers/
lib/
models/
router/
main.go
config contains configuration in JSON and one simple config.go that reads and parses JSON file and fills the Config struct. handlers contains controllers (i.e. handlers of respective METHOD+URL described in router/routes.go). lib contains some DB, request responder and logger logic. models contains structs and their funcs to be mapped from-to JSON and DB. Finally router contains the router and routes definition.
Now I was searching and reading a lot about unit testing REST APIs in GO and found more or less satisfying articles about how to set up a testing server, define routes and test my requests. All fine. BUT only if you want to test a single file!
My problem is now how to set up the testing environment (server, routes, DB connection) for all handlers? With the approach found here (which I find very easy to understand and implement) I have one problem: either I have to run tests separately for each handler or I have to write test suites for all handlers in just one test file. I believe you understand that both cases are not very happy (1st because I need to preserve that running go test runs all tests that succeed and 2nd because having one test file to cover all handler funcs would become unmaintainable).
By now I have succeeded (according to the linked article) only if I put all testing and initializing code into just one func per XYZhandler_test.go file but I don't like this approach as well.
What I would like to achieve is kind of setUp() or init() that runs once with first triggered test making all required variables globally visible and initialized so that all next tests could use them already without the need of instantiating them again while making sure that this setup file is compiled only for tests...
I am not sure if this is completely clear or if some code example is required for this kind of question (other than what is already linked in the article but I will add anything that you think is required, just tell me!
Test packages, not files!
Since you're testing handlers/endpoints it would make sense to put all your _test files in either the handlers or the router package. (e.g. one file per endpoint/handler).
Also, don't use init() to setup your tests. The testing package specifies a function with the following signature:
func TestMain(m *testing.M)
The generated test will call TestMain(m) instead of running the tests
directly. TestMain runs in the main goroutine and can do whatever
setup and teardown is necessary around a call to m.Run. It should then
call os.Exit with the result of m.Run
Inside the TestMain function you can do whatever setup you need in order to run your tests. If you have global variables, this is the place to declare and initialize them. You only need to do this once per package, so it makes sense to put the TestMain code in a seperate _test file. For example:
package router
import (
"testing"
"net/http/httptest"
)
var (
testServer *httptest.Server
)
func TestMain(m *testing.M) {
// setup the test server
router := ConfigureRouter()
testServer = httptest.NewServer(router)
// run tests
os.Exit(m.Run())
}
Finally run the tests with go test my/package/router.
Perhaps you could put the setup code that you want to use from multiple unit test files into a separate package that only the unit tests use?
Or you could put the setup code into the normal package and just use it from the unit tests.
It's been asked before but the Go authors have chosen not to implicitly supply a test tag that could be used to selectively enable function compiles within the normal package files.

How can I test command-line applications using maven?

I work on a complex, multi-module maven project. One of the modules is an executable jar that implements a command-line application. I need to integration test this application. I need to run it several times, with several different command-lines and validate the exit status and stdout/err. However, I can't find a plugin for maven that claims to support this, and also can't track down a JUnit library that supports testing command-line applications.
Before you say 'don't test the main method - instead do bla', in this case I really do mean to test the main method, not some subsidiary functionality. The whole point is to run the application as a user would in its own VM and environment, and validate that it is behaving itself - parsing command-line options correctly, exiting with the write status and hot-loading the right classes from the right plugin jars.
My current hack is to use apache-exec from within a junit test method. It appears to be working, but is quite fiddly to set up.
public void testCommandlineApp()
throws IOException
{
CommandLine cl = new CommandLine(resolveScriptNameForOS("./runme")); // add .sh/.bat
cl.addArgument("inputFile.xml");
exec.setWorkingDirectory(workingDir);
exec.setExitValues(new int[] { 0, 1, 2 });
int exitCode = exec.execute(cl);
assertEquals("Exit code should be zero", 0, exitCode);
}
Why not simply use a shell script, using the maven-exec-plugin to build your classpath?
STDOUT=$(mvn exec:java -DmainClass=yourMainClass --arg1 --arg2=value2)
RETURN_CODE=$?
# validate STDOUT
# validate RETURN_CODE
You can even use something like shunit2 if you prefer a more structured approach.

NAnt, MbUnit, CruiseControl, Selenium - passing settings to the test assembly

I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.
I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:
selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/");
How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?
For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.
I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.
Many thanks if anyone can help.
Thanks for the responses so far.
Environment variables could work, however, we could be running parallel tests via a single test assembly so I wouldn't want settings to be overwritten during execution, which could break another test. Interesting line of thought though, thanks, I reckon I could use that in other areas.
My current solution involves a custom NAnt task build on top of the MbUnit task, which allows me to specify the additional host, port, url settings as attributes. These are then saved as a config file within the build directory and then read in by the test assemblies. This feels a bit "clunky" to me as my tests need to inherit from a specific class. Not too bad but I'd like to have less dependencies and concentrate on the testing.
Maybe I am worrying too much!!
I have a base class for all test fixtures which has the following setup code:
[FixtureSetUp]
public virtual void TestFixtureSetup ()
{
BrowserType = (BrowserType) Enum.Parse (typeof (BrowserType),
System.Configuration.ConfigurationManager.AppSettings["BrowserType"],
true);
testMachine = System.Configuration.ConfigurationManager.AppSettings["TestMachine"];
seleniumPort = int.Parse (System.Configuration.ConfigurationManager.AppSettings["SeleniumPort"],
System.Globalization.CultureInfo.InvariantCulture);
seleniumSpeed = System.Configuration.ConfigurationManager.AppSettings["SeleniumSpeed"];
browserUrl = System.Configuration.ConfigurationManager.AppSettings["BrowserUrl"];
targetUrl = new Uri (System.Configuration.ConfigurationManager.AppSettings["TargetUrl"]);
string browserExe;
switch (BrowserType)
{
case BrowserType.InternetExplorer:
browserExe = "*iexplore";
break;
case BrowserType.Firefox:
browserExe = "*firefox";
break;
default:
throw new NotSupportedException ();
}
selenium = new DefaultSelenium (testMachine, seleniumPort, browserExe, browserUrl);
selenium.Start ();
System.Console.WriteLine ("Started Selenium session (browser type={0})",
browserType);
// sets the speed of execution of GUI commands
if (false == String.IsNullOrEmpty (seleniumSpeed))
selenium.SetSpeed (seleniumSpeed);
}
I then simply supply the test runner with a config. file:
For MSBuild I use environment variables, I create those in my CC.NET config then they would be available in the script. I think this would work for you too.
Anytime I need to integrate with an external entity using NAnt I either end up using the exec task or writing a custom task. Given the information you posted it would seem that writing your own would indeed be a good solution, However you state you're not happy with it. Can you elaborate a bit on why you don't think you current solution is an elegant one?
Update
Not knowing internal details it seems like you've solved it pretty well with a custom task. From what I've heard, that's how I would have done it.
Maybe a new solution will show itself in time, but for now be light on yourself!