JUnit parametrized in Before method executes later and throws ParameterResolutionException - testing

I have test class that consists of #Before method with some parameters, and other test methods.
#Before
#ParameterizedTest
#ValueSource(strings = {"123", "456"})
public void createData(String userId) {
someMethod(userId)
}
#ParameterizedTest
#ValueSource(strings = {"123", "456"})
public void abc(String userId) {}
but it keeps executing abc() first and throws error
org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [public void tests.xxx.createData(java.lang.String) throws java.io.IOException].
I'm quite new to JUnit Parameters. Can Before method be at the same time ParametrizedTest? Without this annotation [ParametrizedTests] it seems not to work as intended, but on the other hand I need this to execute before all other methods. What might be the issue and what's the solution?

Related

RedundantArgumentMatcherException using NSubstitute and NCrunch

I have a sample code (pasted below). I am using Xunit, NSubstitute and NCrunch. When I run the test in Visual Studio's Test Explorer, the test passes. When I debug, the test runs correctly. With NCrunch, I am facing a bizzare behavior, the test passes, and then fails, then it passes and then fails, and it continues like that.
[Fact]
public void Test()
{
var drink = Substitute.For<IDrink>();
var greetings = new Greetings();
var derived = new Derived();
derived.Test(drink, greetings);
}
public class Greetings
{
public string Message { get; set; }
}
public interface IDrink
{
void Prepare(Greetings greetings);
}
public abstract class Base
{
public abstract void Test(IDrink drink, Greetings greetings);
}
public class Derived : Base
{
public override void Test(IDrink drink, Greetings greetings)
{
drink.Prepare(greetings); /////////// The error is here
}
}
public class NullDerived : Derived
{
public override void Test(IDrink drink, Greetings greetings)
{
throw new Exception("No value found");
}
}
The error NCrunch throwing is:
NSubstitute.Exceptions.RedundantArgumentMatcherException: Some argument specifications (e.g. Arg.Is, Arg.Any) were left over after the last call.
This is often caused by using an argument spec with a call to a member NSubstitute does not handle (such as a non-virtual member or a call to an instance which is not a substitute), or for a purpose other than specifying a call (such as using an arg spec as a return value). For example:....
I have tried to remove the parameter from Prepare(Greetings greetings) method, then NCrunch passes the test every single time.
As the error is suggesting, I am not passing the paramaters from the Test correctly.
My question is: What is the correct way of passing the greetings object to Prepare method. I have tried Arg.Any but it didn't work.
Any help is appreciated.
Edit 1:
I am seeing the same behvarior using Reshaper's Unit Test Coverage.

Is there a way to have the #MethodSource arguments parameters derived from another method

I have a Junit 5 non static parameterized test where I am using #MethodSource to get the test data.
The Method Source arguments are getting the data from other methods as below code. I made the #MethodSource non static by having a
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
The fullDomain parameter in the #MethodSource is derived from the method getFullDomain() in the registrationPage which is also non static . I #Autowired the RegistrationPage in the BaseTest and using it by extending in my Junit5SampleTest Class
When I run the test the fullDomain is returning null. Is there a way to fix this or can I use any others like #ArgumentSource to fix this.
I will need to get the Arguments.of("Successful Regisration", fullDomain) data from different classes and its methods.
Base Test:
public class BaseTest {
#Autowired
protected RegistrationPage registrationPage;
}
Test Class:
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class Junit5SampleTest extends BaseTest {
String fullDomain = registrationPage.getFullDomain();
Stream<Arguments> registrationInputParameters() {
return Stream.of(
Arguments.of("Successful Regisration", fullDomain)
}
#ParameterizedTest()
#MethodSource("registrationInputParameters")
public void junit5(String testName, String fullDomain){
System.out.println(testName);
open(fullDomain);
}
}

Using InjectMock on Object with private static final fields failing

I am writing test cases for a legacy code which for some reason we dont want to change.
The code is something like this
public class ToBeTested{
private static final String field1=SomeUtil.getProperty("somekey");
#AutoWired
Someservice service;
}
In my Junit I am using powermock with mockito and did something like this
public class myTestClass{
#Mock
SomeService service;
#InjectMock
ToBeTested tested;
}
However, InjectMocks fails to create the object for ToBeTested since the final fields are not provided
So I implemented a #BeforeClass and mocked the static method of SomeUtil. This works if i have only one test case. But for more than one test case, only one passes and others are failing with same error that
cannot instantiate #injectmocks field named you haven't provided the instance at field declaration
I have been able to resolve this by using something as below:
public class myTestClass{
#Mock
SomeService service;
ToBeTested tested;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
mockStatic(SomeUtil.class);
when(SomeUtil.getProperty(anyString())).thenReturn("test");
toBeTested=new ToBeTested(); Whitebox.setInternalState(toBeTested,"someService",someService);
}
}
However am not a fan of using reflection in Junit which WhiteBox does internally.
Is there a better way to do this?
Edit: Adding the snippet of code as suggested by Rann in comment
#RunWith(PowerMockRunner.class)
#PrepareForTest(SomeUtil.class)
public class myTestClass{
#Mock
SomeService service;
#InjectMock
ToBeTested tested;
#BeforeClass
public static void doBeforeClass(){
mockStatic(SomeUtil.class);
when(SomeUtil.getProperty(anyString())).thenReturn("test");
}
#Test
public void test1(){
tested.doSomethingFor1();
}
#Test
public void test2(){
tested.doSomethingFor2();
}
}
test1 passes fine. for test2 i get an exception as
Caused by: org.mockito.exceptions.base.MockitoException:
Cannot instantiate #InjectMocks field named 'tested' of type 'class com.xyz.ToBeTested'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
at org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:72)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:64)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
... 23 more
Caused by: java.lang.NullPointerException
at com.xyz.SomeUtil.getProperty(SomeUtil.java:42)

Assertion in selenium webdriver -report showing only falied methods, not passed methods

In my selenium TestNG class, there are some
methods, like method1, method2 etc.
I have added fail and success conditions to each method.
public class TestNGClass {
public void method1(String value) throws Exception {
if(value.equals("PASS"){
org.testng.Assert.assertTrue(condition, message);
}
}
//This is another method
public void method2(String value) throws Exception {
if(value.equals("FAIL"){
org.testng.Assert.fail(message);
}
}
But after the TestNG class execution, in the Test-Output folder "Index.html" will be created, which shows only the failed methods. How to display the passed methods also (custom report) .?
Thank you
Convert your test methods using #Test annotation. Modified Code Snippet:
public class TestNGClass {
#Test
public void method1(){
Assert.assertTrue(condition, "Your Message goes here");
}
//This is another method
#Test
public void method2(){
Assert.fail("Your Message goes here");
}
Now, you will have your testcases reported.

to run beforemethod before dataprovider

We are trying to automate the test cases to run in parallel .For this we are using Testng annotations, like #test ,#before method and #data provider. Problem we are facing is, for all the #test the #before method is running but only for the test having #data provider it is getting run after #dataprovider. That is the problem
Our code looks like this
Class Test()
{
Public Test()
{
// code
}
#Beforemethod
Public BeforeTest(){
//Initializing an object for a class where all methods in which we are running in the #Test methods
}
#Dataprovider
Public Dataprovider()
{
//code
}
#Aftermethod
Public Aftermethod()
{
Null the object created in the #before method
}
#Test
Public test1(){
//code
}
#Test(groups={"tests_verifyDataEntryScenarios"},enabled=true, dataProvider = “name”)
Public Test2()
{
//code
}
Problem coming with the ‘#Test test2()’, as it has data provider, instead of calling before method first it is calling data provider first but the object used in #dataprovider was initialized in the #beforemethod, As the dataprovider calling first for test2 it is throwing Null pointer exception. Is there any way to call the ‘#beforemethod’ before #Dataprovider.