Junit 5 : How to provide names to Parameterized Test - junit5

I have simple parameterized test case like below
#ParameterizedTest
#ValueSource(strings = { "Hello", "World","Test" })
void withFixValues(String word) {
System.out.println(word);
assertNotNull(word);
}
But in case test fails , it not easy to check for which parameter value test is failing. Is there any way we can name Parameterized test cases based on parameters?

We can provide name using name attribute.
#ParameterizedTest(name = "withSomeName #{index} with Value [{arguments}]")
#ValueSource(strings = { "Hello", "World","Test" })
void withFixValues(String word) {
System.out.println(word);
assertNotNull(word);
}

Related

test objects created inside a method jmockit

The method which I wanted to test looks like:
public void method1(String str) {
ParmaObjectRequest request = new ParmaObjectRequest(str);
this.instanceVar.save(request);
}
I wanted to test if this.instanceVar.save is called with an ParmaObjectRequest object with str value using jmockit.
The test case I have written looks like below and I am able to test that my method is called 1 times but not the parameter inside it.
#Test
public void testMethod1() {
new Expectations() {
{
this.instanceVar.save((ParmaObjectRequest) any);
times = 1;
}
};
testObject.method1("dummyString");
}
But I also wanted to test that this.instanceVar.save is called with object containing "dummyString".
In the Expectations block, change "this.instanceVar" to "testObject.instanceVar"

JUnit Paramterized test Json/Text

Hi I have 2 tests methods, that are almost same, but is one difference between them, I would like to create a parameterized test method that have valuesource json and text/plain, how to create a parameterized test from these 2 methods.
#Test
public void shouldTestReturnWorkInText()
{
given().header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE)
.when()
.get(getContextBaseUrl())
.peek()
.then()
.statusCode(HttpStatus.OK.value())
.body(equalTo("work"));
}
#Test
public void shouldTestReturnWorkInJSON()
{
given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.when()
.get(getContextBaseUrl())
.peek()
.then()
.statusCode(HttpStatus.OK.value())
.body("message", equalTo("work"));
}
The two tests are different only on the last assertion (body()) so you can extract a variable up to statusCode() expression and then do the specific body() assertion depending on content type provided as a test parameter
#ValueSource(strings = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE })
void shouldTestReturnWorkFor(String contentType) {
ValidatableResponse response = given().header(HttpHeaders.ACCEPT, contentType)
.when()
.get(getContextBaseUrl())
.peek()
.then()
.statusCode(HttpStatus.OK.value());
if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
response.body("message", equalTo("work"));
} else if (contentType.equals(MediaType.TEXT_PLAIN_VALUE)) {
response.body(equalTo("work"));
} else {
throw new IllegalArgumentException("Unsupported content type: " + contentType);
}
}

How to add multiple filter conditions based on incoming parameters to the Exposed DAO API ".find"

I am writing a dropwizard application using kotlin and one of the resource methods will receives multiple parameters(email, phone, is_deleted, etc). Based on the incoming query params, I have to filter the table. I am using DAO API of Exposed to construct the query.
val result = User.find { //SqlExpressionBuilder
Users.isDeleted eq false
Users.email eq "so#soso.com"
}.sortedByDescending { it.createdAt }
How to add multiple where conditions to the query based on the map of query params using a for in loop?
I had to solve the problem using DSL. Seems like DAO doesn't have such provision to create such adhoc query.
val query = Users.selectAll()
for((k, v) in params) {
val value = URLDecoder.decode(v, "UTF-8")
when(value) {
"email" -> query.andWhere { Users.email eq value }
"phone" -> query.andWhere { Users.phone eq value }
}
}
return query.andWhere { Users.isDeleted.eq(false) }
As #Tapac mentioned, one can use User.wrapRows(query).sortedByDescending() also to frame such query but again one have to use DSL.
Hope that helps someone.
It is possible:
val email = URLDecoder.decode("email", "UTF-8")
val phone = URLDecoder.decode("phone", "UTF-8")
Users.find {
if (email != null) (Users.email eq email) else Op.TRUE
.and(if (phone != null) (Users.phone eq phone) else Op.TRUE)
}

TestNG Test Case failing with JMockit "Invalid context for the recording of expectations"

The following TestNG (6.3) test case generates the error "Invalid context for the recording of expectations"
#Listeners({ Initializer.class })
public final class ClassUnderTestTest {
private ClassUnderTest cut;
#SuppressWarnings("unused")
#BeforeMethod
private void initialise() {
cut = new ClassUnderTest();
}
#Test
public void doSomething() {
new Expectations() {
MockedClass tmc;
{
tmc.doMethod("Hello"); result = "Hello";
}
};
String result = cut.doSomething();
assertEquals(result, "Hello");
}
}
The class under test is below.
public class ClassUnderTest {
MockedClass service = new MockedClass();
MockedInterface ifce = new MockedInterfaceImpl();
public String doSomething() {
return (String) service.doMethod("Hello");
}
public String doSomethingElse() {
return (String) ifce.testMethod("Hello again");
}
}
I am making the assumption that because I am using the #Listeners annotation that I do not require the javaagent command line argument. This assumption may be wrong....
Can anyone point out what I have missed?
The JMockit-TestNG Initializer must run once for the whole test run, so using #Listeners on individual test classes won't work.
Instead, simply upgrade to JMockit 0.999.11, which works transparently with TestNG 6.2+, without any need to specify a listener or the -javaagent parameter (unless running on JDK 1.5).

Rhino moq Property.value constraint

My following straight forward test doesn't pass (Though I feel it should). Either I am missing something or is not clear of Property.value constraint. please help me in understanding concept of property.value constraint.
public interface ISomeInterface
{
void SomeMethod(string x, string y);
}
public class SomeClassTest
{
[Test]
public void SomeMethodTest()
{
MockRepository mocks = new MockRepository();
ISomeInterface mockservice = mocks.StrictMock<ISomeInterface>();
using (mocks.Record())
{
mockservice.SomeMethod("xValue", "yValue");
LastCall.Constraints(Property.Value("x", "xValue"),
Property.Value("y", "yValue"));
}
mockservice.SomeMethod("xValue", "yValue");
mocks.Verify(mockservice);
}
}
Exception raised:
Rhino.Mocks.Exceptions.ExpectationViolationException : ISomeInterface.SomeMethod("xValue", "yValue"); Expected #0, Actual #1.
ISomeInterface.SomeMethod(property 'x' equal to xValue, property 'y' equal to yValue); Expected #1, Actual #0.
I would recommend you the following syntax (AAA syntax):
// arrange
var mockservice = MockRepository.GenerateMock<ISomeInterface>();
// act
mockservice.SomeMethod("xValue", "yValue");
// assert
mockservice.AssertWasCalled(
x => x.SomeMethod("xValue", "yValue")
);
This sample class illustrates the options for asserting methods were called with appropriate properties:
public class UsesThing
{
private IMyThing _thing;
public UsesThing(IMyThing thing)
{
_thing = thing;
}
public void DoTheThing(int myparm)
{
_thing.DoWork(myparm, Helper.GetParmString(myparm));
}
public void DoAnotherThing(int myparm)
{
AnotherThing thing2 = new AnotherThing();
thing2.MyProperty = myparm + 2;
_thing.DoMoreWork(thing2)
}
}
Using simple values for assertions may work for methods like the DoTheThing method which uses value types:
[Test]
public void TestDoTheThing()
{
IMyThing thing = MockRepository.GenerateMock<IMyThing>();
UsesThing user = new UsesThing(thing);
user.DoTheThing(1);
thing.AssertWasCalled(t => t.DoWork(1, "one");
}
However, if you need to create an object in your method and pass it as a parameter like in the DoAnotherThing method, this approach will not work since you will not have a reference to the object. You have to check the property values of the unknown object, like this:
[Test]
public void TestDoAnotherThing()
{
IMyThing thing = MockRepository.GenerateMock<IMyThing>();
UsesThing user = new UsesThing(thing);
user.DoAnotherThing(1);
thing.AssertWasCalled(t => t.DoMoreWork(null), t => t.IgnoreArguments().Constraints(Property.Value("MyProperty", 3))));
}
The new Rhino syntax would look like the following, but I am crashing VS 2008 when I use it:
thing.AssertWasCalled(t => t.DoMoreWork(Arg<AnotherThing>.Matches(Property.Value("MyProperty", 3))));