my requirement is data {"1"} pass to test1 method, data {"2"} pass to test2 method and each method execute one time only.
Please help
public void Dataread{
#DataProvider (name = "data"){
public Object[][] dataMethod(){
return new Object[][] {{"1"}, {"2"}};
}
#Test (dataProvider = "data")
public void test1 (String val) {
System.out.println("Test1 : " + val);
}
#Test (dataProvider = "data")
public void test2 (String val) {
System.out.println("Test2 : " + val);
}
}
Expected output:
Test1 : 1
Test2 : 2
Related
In the below code I want to mock DB operation of GetTitle(int id) in FooBase class. But I want to test validations part in overridden GetTitle(int id).
I want to test overridden method but mock the base method
How I can mock virtual method and testing the overridden of it?
public abstract class FooBase
{
public virtual string GetTitle(int id) { return "Title From DB" /*Select From DB*/; }
}
public class Foo : FooBase
{
public override string GetTitle(int id)
{
if (id < 0)
return "Invalid id";
/*Doing somethings like other validations and etc*/
return $"Valid ID ({base.GetTitle(id)})";
}
}
public class FooTests
{
[Fact]
public void GetTitle() // Fails
{
// Arrange
var expectedID = 1;
var expectedResult = "Test";
var fooMock = new Mock<Foo>();
fooMock.Setup(x => x.GetTitle(It.IsAny<int>())).Returns(expectedResult);
var foo = fooMock.Object;
// Act
var title = foo.GetTitle(expectedID);
// Assert
fooMock.Verify(x => x.GetTitle(It.Is<int>(c => expectedID == c)), Times.Once);
Assert.Equal($"Valid ID ({expectedResult})", title);
}
}
If you can separate your logic into a different method (what might be a better design too), than you can use Moq's CallBase property to make the test call the mocked method.
public abstract class FooBase
{
public virtual string GetTitle(int id) { return "Title From DB" /*Select From DB*/; }
}
public class Foo : FooBase
{
public virtual string GetValidatedTitle(int id)
{
if (id < 0)
return "Invalid id";
/*Doing somethings like other validations and etc*/
return $"Valid ID ({GetTitle(id)})";
}
}
public class FooTests
{
[Fact]
public void GetTitle() // Now Passes
{
// Arrange
var expectedID = 1;
var expectedResult = "Test";
var fooMock = new Mock<Foo>() { CallBase = true };
fooMock.Setup(x => x.GetTitle(It.IsAny<int>())).Returns(expectedResult);
var foo = fooMock.Object;
// Act
var title = foo.GetValidatedTitle(expectedID);
// Assert
fooMock.Verify(x => x.GetTitle(It.Is<int>(c => expectedID == c)), Times.Once);
Assert.Equal($"Valid ID ({expectedResult})", title);
}
}
I have an Interface to check vowel and to return a char as
public interface IVowChecker
{
bool VowCheck(char a);
char ReturnChar(int n);
Student GetStudentById(int n);
}
It's concrete class implementation
public class VowChecker:IVowChecker
{
public bool VowCheck(char a)
{
if (a == 'a' || a == 'A')
return true;
return false;
}
public char ReturnChar(int n)
{
return (char)n;
}
public Student GetStudentById(int n)
{
var list = new []
{
new Student{RollNo=1,Name="A"},
new Student{RollNo=2,Name="B"},
new Student{RollNo=3,Name="C"},
new Student{RollNo=4,Name="D"},
new Student{RollNo=5,Name="E"},
new Student{RollNo=6,Name="F"},
};
var student = from i in list
where i.RollNo == n
select i;
return student.FirstOrDefault();
}
}
And a service using this VowChecker
public class MyCharService
{
private readonly IVowChecker _checker;
public MyCharService(IVowChecker checker)
{
_checker = checker;
}
public bool CheckInput(char a)
{
return _checker.VowCheck(a);
}
public char ReturnChar(int a)
{
return _checker.ReturnChar(a);
}
public Student GetStudentById(int n)
{
return _checker.GetStudentById(n);
}
}
I am using Xunit testing framework for unit testing and Moq library.
My unit test code is
public class MyCharServiceShould
{
...
[Theory]
[InlineData(65)]
[InlineData(68)]
public void BeAbleToReturnChar(int n)
{
var service = new Mock<IVowChecker>();
service.Setup(i => i.ReturnChar(n)).Returns('A');
var obj = new MyCharService(service.Object);
var result = obj.ReturnChar(n);
}
[Theory]
[InlineData(2)]
public void BeAbleToRetrieveStudent(int n)
{
var service = new Mock<IVowChecker>();
service.Setup<Student>(i => i.GetStudentById(n)).Returns<Student>(f => (Student)f);
var ob = new MyCharService(service.Object);
var res = ob.GetStudentById(2);
Assert.Equal(res.Name, "B");
}
}
My Student class
public class Student
{
public int RollNo{ get; set; }
public string Name { get; set; }
}
I have used a debugger in the last line of my test and checked the values of both the tests. For the 1st test I am expecting 'A' as the result and for the 2nd test I am expecting 'D' as the result. But in both the cases I am getting 'A' as the result. Can anyone kindly help me out where I am missing out the concept. Thank you.
The problem is that the setup for ReturnChar
service.Setup(i => i.ReturnChar(n)).Returns('A');
says,
Whenever ReturnChar() is called, give an answer of 'A'
It ignores the input 'n' and just returns 'A'. If you want it to return a different character for each test you will need to tweak the setup.
Perhaps
mockService.Setup(mk => mk.ReturnChar(It.IsAny<int>())).Returns<int>(n => (char)n);
EDIT: Extension to show returning objects (and fixed syntax on previous answer)
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IService
{
Student FindStudentById(int id);
}
[TestMethod]
public void FindStudents()
{
var students = new[]
{
new Student {Id = 1, Name = "Mon" },
new Student {Id = 2, Name = "Tue" },
new Student {Id = 3, Name = "Wed" },
new Student {Id = 4, Name = "Thu" },
};
var mockService = new Mock<IService>();
mockService.Setup(mk => mk.FindStudentById(It.IsAny<int>())).Returns<int>(id => students.First(s => s.Id == id));
Assert.AreEqual("Wed", mockService.Object.FindStudentById(3).Name);
}
I have trouble using #UsingDataSet in my project.
Example in manual https://docs.jboss.org/author/display/ARQ/Persistence
doesn`t helps.
I have simple entity:
#Entity(name = "game")
#Table(name = "game_entity", schema = "graph")
#GenericGenerator(name="uuid2", strategy = "uuid2")
public class Game implements Serializable {
private static final long serialVersionUID = -4832711740307931146L;
private UUID id;
private String name;
#Id
#GeneratedValue(generator="uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotNull
#Column(name = "name", length = 256, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object value) {
if (!(value instanceof Game)) {
return false;
}
if (value == this) {
return true;
}
Game obj = (Game) value;
if (!obj.getId().equals(getId())) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result = 29;
result += 29 * (getId() != null ? getId().hashCode() : 0);
result += 29*(getName() != null ? getName().hashCode() : 0);
return result;
}
}
And .yml file
game_entity:
- id : d5c58afd-7c99-41bb-ab0a-6357bfddfe14
name : Call of Duty
My test:
public class MyTest extends Arquillian {
#PersistenceContext(unitName = "spo")
private EntityManager em;
#Test
#UsingDataSet("datasets/gameDataSet.yml")
public void testAttribute() {
System.out.println("Hello world !");
}
#Deployment
public static WebArchive createArchive() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, "myTest.war")
.addAsLibraries(
// blah-blah-blah
)
.addAsResource("my-persistence.xml", "META-INF/persistence.xml")
//.addAsResource("datasets/gameDataSet.yml", "datasets/gameDataSet.yml") // do I need to add this to archive ??
.addAsWebInfResource("META-INF/beans.xml", "beans.xml")
.setWebXML("web.xml")
;
return war;
}
}
When I run this test I getting 2 "strange" exeptions.
Sometimes:
Caused by: org.dbunit.dataset.NoSuchColumnException: game_entity.ID - (Non-uppercase input column: id) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
But there are 2 columns in database! "id" and "name"
Sometimes, even more strange exception:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "info_resource_attributes" does not exist
This is cross-table for another 2 entities, it exist in archive and myPersistence.xml but I dont use them in this test.
I use Wildfly 10 and Postgres 9.5. Without #UsingDataSet everything fine.
But I dont want programmaticaly hardcode data for tests like that:
Entity newEntityForTest = new Entity();
newEntityForTest.setA(...);
newEntityForTest.setB(...);
newEntityForTest.setC(...);
em.persist(newEntityForTest);
// testing ...
em.remove(newEntityForTest);
i'm developping a restful web service that extract data (messages) from my database and return all messages!
every single message is a MsgBean ( with an id, contenu, from, numexp,... )
the web service couldn't return a table so i created a new object that contain a table (msgTable) of MsgBean !
while running my web service on the rest console, i got this error :
Etat HTTP 500 - java.lang.NullPointerException
type Rapport d''exception
message java.lang.NullPointerException
description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.
Click to see the rest of error
my MsgBean is :
#XmlRootElement
public class MsgBean implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String frommm;
private String contenu;
private String DateEnvoi;
private String NumExp;
private int idu;
public MsgBean(){};
#XmlElement
public int getIdu() {
return idu;
}
public void setIdu(int idu) {
this.idu = idu;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getFrommm() {
return frommm;
}
public void setFrommm(String frommm) {
this.frommm = frommm;
}
#XmlElement
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
#XmlElement
public String getDateEnvoi() {
return DateEnvoi;
}
public void setDateEnvoi(String DateEnvoi) {
this.DateEnvoi = DateEnvoi;
}
#XmlElement
public String getNumExp() {
return NumExp;
}
public void setNumExp(String NameExp) {
this.NumExp = NameExp;
}
}
my msgTabl is :
#XmlRootElement
public class msgTabl implements Serializable {
String test;
MsgBean[] m = new MsgBean[100];
public msgTabl(){};
#XmlElement
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
#XmlElement
public MsgBean getM(int i) {
return m[i];
}
public void setM(int i, MsgBean mb) {
this.m[i].setId(mb.getId());
this.m[i].setIdu(mb.getIdu());
this.m[i].setFrommm(mb.getFrommm());
this.m[i].setNumExp(mb.getNumExp());
this.m[i].setDateEnvoi(mb.getDateEnvoi());
this.m[i].setContenu(mb.getContenu());
}
}
and here is the web service that i did test with :
#GET
#Path("/historiquemethod")
#Produces("application/json")
//#Produces("text/plain")
public msgTabl historique(
#QueryParam("pseudo") String pseudo,
#QueryParam("motDePasse") String motDePasse
) {
msgTabl tab = new msgTabl();
MsgBean ms = new MsgBean();
// set information into our msg to test
ms.setContenu("contenu");
ms.setFrommm("8080");
ms.setNumExp("2584126");
ms.setId(1);
ms.setIdu(2);
ms.setDateEnvoi("date");
// set the message into the first table case
tab.setM(0, ms);
tab.setTest("ok");
return tab;
}
In setM method do this in first line :
this.m[i] = new MsgBean();
Problem is that you have instantiated your array but the objects are null inside that array. So you need to first instantiate the object at required index and then use it.
UPDATE FOR COMMENT
Make a getter method for your m like this getM() and annotate it with XmlElement(Remove the annotation from your current overloaded getM(int i) method). The method getM(int i) cannot be used by JAXB, since jaxb needs simple getter and setter for your properties.
With the following:
#XmlRootElement(name = "purchase")
#XmlType(propOrder = {"memberId", "propertyA", "propertyB", "propertyC", "listProps"})
public class ClassA {
private Long memberId;
private Integer propertyA;
private String propertyB;
private Integer propertyC;
private List<ClassB> listProps;
public ClassA() {
}
#XmlElement(name = "memberId")
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
#XmlElement(name = "propertyA")
public Integer getPropertyA() {
return propertyA;
}
public void setPropertyA(Integer propertyA) {
this.propertyA = propertyA;
}
#XmlElement(name = "propertyB")
public String getPropertyB() {
return propertyB;
}
public void setPropertyB(String propertyB) {
this.propertyB = propertyB;
}
#XmlElement(name = "propertyC")
public Integer getPropertyC() {
return propertyC;
}
public void setPropertyC(Integer propertyC) {
this.propertyC = propertyC;
}
#XmlElement(name = "listProps")
public List<ClassB> getListProps() {
return listProps;
}
public void setListProps(List<ClassB> listProps) {
this.listProps = listProps;
}
}
#XmlRootElement(name = "listProp")
#XmlType(propOrder = {"countA", "countB"})
public class ClassB {
private int countA;
private int countB;
public ClassB() {
}
public int getCountA() {
return countA;
}
public int getCountB() {
return countB;
}
#XmlElement(name = "countA")
public void setCountA(int countA) {
this.countA = countA;
}
#XmlElement(name = "countB")
public void setCountB(int countB) {
this.countB = countB;
}
}
When I try and marshal / unmarshal objects of type ClassA, the listProps is always empty regardless of how many objects I have put in it. Can anyone tell me what I am doing wrong?
When I marshal your model classes as follows:
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ClassA.class);
List<ClassB> classBs = new ArrayList<ClassB>();
classBs.add(new ClassB());
classBs.add(new ClassB());
ClassA classA = new ClassA();
classA.setListProps(classBs);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(classA, System.out);
}
}
I get the following output, so there is no problem with your list property:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchase>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
</purchase>
As I understand your problem is to unmarshal list of values which you have marshaled. The same problem I faced with jaxb-impl lib +2.2.x when unmarshaling results into empty list while XML contains at least 1 element. Try to instantiate list if it is null in method getListProps so JAXB could populate it. I feel like the problem is in List + XmlAccessorType.PROPERTY as it does not create list by default and tries to use existing one, because it is null setListProps is called with empty collection.