Monday, 2 August 2021

Junit5: ParameterizedTest: String to Object conversion

Junit provides a mechanism to convert from strings to target types. Following conditions should met by the target type or class.

 

Target type must declares exactly one suitable factory method or a factory constructor as defined below.

 

a.   factory method: a non-private, static method declared in the target type that accepts a single String argument and returns an instance of the target type. The name of the method can be arbitrary and need not follow any particular convention.

 

b.   factory constructor: a non-private constructor in the target type that accepts a single String argument. Note that the target type must be declared as either a top-level class or as a static nested class.

 

What if target type has multiple factory methods in the target class?

If multiple factory methods are discovered, they will be ignored.

 

What if target type has both factory method and factory constructor?

Factory method will be used instead of the constructor.

 

Student.java

package com.sample.app.model;

public class Student {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public static Student getStudent(String name) {
		Student student = new Student();
		student.name = name;

		return student;
	}

}

 

StringToObjectConverterTest.java

package com.sample.app;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import com.sample.app.model.Student;

public class StringToObjectConverterTest {
	
	@ParameterizedTest
	@ValueSource(strings = "Gopi")
	void test1(Student student) {
	    assertEquals("Gopi", student.getName());
	}
	
}

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment