how to write junit for this method - junit

how can i write junit for my AddressBO class ?
if 2 address are same return RED....
public class AddressBO {
public String checkAddresses(String address1, String address2) {
if(address1.equals(address2))
return "RED";
else if(address1.equalsIgnoreCase(address2))
return "BLUE";
else if(address1.replaceAll("\\s", "").equals(address2.replaceAll("\\s", "")))
return "YELLOW";
return "GREEN";
}
}
And test class is ...........................
#Test
public void testCheckAddressesRed() {
//fill the code
}
public void testCheckAddressesBlue() {
//fill the code
}
public void testCheckAddressesYellow() {
//fill the code
}
public void testCheckAddressesGreen() {
//fill the code
}

It works
public class AddressJUnit {
#Before
public void createBoInstance() {
AddressBO ad=new AddressBO();
}
#Test
public void testCheckAddressesRed() {
AddressBO ad=new AddressBO();
assertEquals("RED", ad.checkAddresses("pune", "pune"));
}
#Test
public void testCheckAddressesBlue() {
AddressBO ad=new AddressBO();
assertEquals("BLUE", ad.checkAddresses("pUne", "pune"));
}
#Test
public void testCheckAddressesYellow() {
AddressBO ad=new AddressBO();
assertEquals("YELLOW", ad.checkAddresses("pu ne", "pune"));
}
#Test
public void testCheckAddressesGreen() {
AddressBO ad=new AddressBO();
assertEquals("GREEN", ad.checkAddresses("pu", "pune"));
}

Related

JUnit and EntityTransaction

My base class
public abstract class JPABaseIT {
protected static EntityManagerFactory emf;
protected static EntityManager em;
protected static EntityTransaction tx;
protected JPABaseIT() {
emf = Persistence.createEntityManagerFactory(getPersistenceUnit());
em = emf.createEntityManager();
tx = em.getTransaction();
}
protected abstract String getPersistenceUnit();
protected abstract String getCleanQuery();
#Before
public void initTx(){
tx.begin();
em.createNativeQuery(getCleanQuery()).executeUpdate();
tx.commit();
tx.begin();
}
#After
public void endTx() {
if(tx != null && tx.isActive()) {
if(!tx.getRollbackOnly()) {
tx.commit();
} else {
tx.rollback();
}
}
}
#AfterClass
public static void tearDownEM() {
if (em != null) {
em.clear();
if (em.isOpen()) {
em.close();
}
if (emf.isOpen()) {
emf.close();
}
}
}
}
My test (without building a context, using EM directly)
public class FooBeanIT extends JPABaseIT {
protected FooBean service;
public FooBeanIT() {
service = new FooBean();
service.setEntityManager(em);
}
#Override
protected String getPersistenceUnit() {
return "foo-TEST";
}
#Override
protected String getCleanQuery() {
return "TRUNCATE TABLE FOO;";
}
#Test
public void updateFoo_test() {
service.addFoo(); // -> em.persist()
service.updateFooStatus(); // -> em.createNamedQuery().executeUpdate()
Foo actual = service.getFooById(); // -> em.find()
}
}
actual is returned but is not updated. I've tried to do tx.commit(); tx.begin(); after the update but is like being ignored. How should I get my entity updated in this kind of tests with multiple operations?

Inheritance in Json Response Spring boot

I have two classes, A and B:
class A{
private int numberOne;
private int numberTwo;
public int getNumberOne() {
return numberOne;
}
public void setNumberOne(int numberOne) {
this.numberOne = numberOne;
}
public int getNumberTwo() {
return numberTwo;
}
public void setNumberTwo(int numberTwo) {
this.numberTwo = numberTwo;
}
}
class B extends A {
private int numberThree;
public int getNumberThree() {
return numberThree;
}
public void setNumberThree(int numberThree) {
this.numberThree = numberThree;
}
}
How do I can like this:
ResponseEntity<A> someMethod(){
return new B(1,2,3);
}
json
{
"numberOne":"1",
"numberTwo":"2"
}
ResponseEntity<B> someMethod(){
return new B(1,2,3);
}
json
{
"numberOne":"1",
"numberTwo":"2",
"numberThree":"3"
}
How can I use JSON ignoring in Spring Boot which I want?
You create new class
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
A.class
public class A {
public A(int numberOne, int numberTwo) {
this.numberOne = numberOne;
this.numberTwo = numberTwo;
}
#JsonView(Views.Public.class)
private int numberOne;
#JsonView(Views.Public.class)
private int numberTwo;
public int getNumberOne() {
return numberOne;
}
public void setNumberOne(int numberOne) {
this.numberOne = numberOne;
}
public int getNumberTwo() {
return numberTwo;
}
public void setNumberTwo(int numberTwo) {
this.numberTwo = numberTwo;
}
}
B.class
public class B extends A{
#JsonView(Views.Internal.class)
private int numberThree;
public B(int numberOne, int numberTwo) {
super(numberOne, numberTwo);
}
public B(int numberOne, int numberTwo, int numberThree) {
super(numberOne, numberTwo);
this.numberThree = numberThree;
}
public int getNumberThree() {
return numberThree;
}
public void setNumberThree(int numberThree) {
this.numberThree = numberThree;
}
}
Controller
#GetMapping("/a-method")
#JsonView(Views.Public.class)
public ResponseEntity<A> getA(){
return ResponseEntity.ok(new B(1,2,3));
}
#GetMapping("/b-method")
#JsonView(Views.Internal.class)
public ResponseEntity<B> getB(){
return ResponseEntity.ok(new B(1,2,3));
}

415 error while trying to post json array to spring rest controller

My json request is as follows
{
"division":"XX",
"category":"XX",
"operation":"XXX",
"transactionId":"XX",
"trackNumber":"XXx",
"attentionReason":"",
"carNeedAttention":"",
"chargableDamage":"X",
"missingItems":"",
"offences":"N",
"outInAgentNumber":"XX",
"cList":{
{
"id":"230",
"elementCode":"XXX",
"value":"XXX",
"comment":"XX",
"label":"",
"uiComponent":"",
"featureType":""
}
},
"outInCprNumber":"XX",
"outInDate":"",
"outInDuration":"",
"outInFuel":"75",
"outInKm":"9999",
"outInRem1":"",
"outInRem2":"",
"outInRem3":"",
"userName":"XX",
"vehicleRetBy":""
}
I have a spring rest controller class
#Controller
#RequestMapping("/services")
public class CheckListController {
#RequestMapping(value = "/checkList", method = RequestMethod.POST, consumes="application/json",produces="application/json")
public ModelMap updateCheckList(#RequestBody CheckList checkList){
ModelMap modelMap = new ModelMap();
return modelMap;
}
}
CheckList class is as follows
import java.util.List;
public class CheckList {
String division;
String category;
String operation;
String transactionId;
String trackNumber;
String attentionReason;
String carNeedAttention;
String chargableDamage;
String missingItems;
String offences;
String outInAgentNumber;
List<MetaData> cList;
String outInCprNumber;
String outInDate;
String outInDuration;
String outInFuel;
String outInKm;
String outInRem1;
String outInRem2;
String outInRem3;
String userName;
String vehicleRetBy;
String updateMasterImage;
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTrackNumber() {
return trackNumber;
}
public void setTrackNumber(String trackNumber) {
this.trackNumber = trackNumber;
}
public String getAttentionReason() {
return attentionReason;
}
public void setAttentionReason(String attentionReason) {
this.attentionReason = attentionReason;
}
public String getCarNeedAttention() {
return carNeedAttention;
}
public void setCarNeedAttention(String carNeedAttention) {
this.carNeedAttention = carNeedAttention;
}
public String getChargableDamage() {
return chargableDamage;
}
public void setChargableDamage(String chargableDamage) {
this.chargableDamage = chargableDamage;
}
public String getMissingItems() {
return missingItems;
}
public void setMissingItems(String missingItems) {
this.missingItems = missingItems;
}
public String getOffences() {
return offences;
}
public void setOffences(String offences) {
this.offences = offences;
}
public List<MetaData> getcList() {
return cList;
}
public void setcList(List<MetaData> cList) {
this.cList = cList;
}
// public AccessoryList getAccessoryList() {
// return accessoryList;
// }
//
// public void setAccessoryList(AccessoryList accessoryList) {
// this.accessoryList = accessoryList;
// }
public String getOutInCprNumber() {
return outInCprNumber;
}
public void setOutInCprNumber(String outInCprNumber) {
this.outInCprNumber = outInCprNumber;
}
public String getOutInDate() {
return outInDate;
}
public void setOutInDate(String outInDate) {
this.outInDate = outInDate;
}
public String getOutInRem1() {
return outInRem1;
}
public void setOutInRem1(String outInRem1) {
this.outInRem1 = outInRem1;
}
public String getOutInRem2() {
return outInRem2;
}
public void setOutInRem2(String outInRem2) {
this.outInRem2 = outInRem2;
}
public String getOutInRem3() {
return outInRem3;
}
public void setOutInRem3(String outInRem3) {
this.outInRem3 = outInRem3;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getVehicleRetBy() {
return vehicleRetBy;
}
public void setVehicleRetBy(String vehicleRetBy) {
this.vehicleRetBy = vehicleRetBy;
}
public String getUpdateMasterImage() {
return updateMasterImage;
}
public void setUpdateMasterImage(String updateMasterImage) {
this.updateMasterImage = updateMasterImage;
}
public String getOutInAgentNumber() {
return outInAgentNumber;
}
public void setOutInAgentNumber(String outInAgentNumber) {
this.outInAgentNumber = outInAgentNumber;
}
public String getOutInDuration() {
return outInDuration;
}
public void setOutInDuration(String outInDuration) {
this.outInDuration = outInDuration;
}
public String getOutInFuel() {
return outInFuel;
}
public void setOutInFuel(String outInFuel) {
this.outInFuel = outInFuel;
}
public String getOutInKm() {
return outInKm;
}
public void setOutInKm(String outInKm) {
this.outInKm = outInKm;
}
}
MetaData is as folows
public class MetaData{
Integer id;
String label;
String uiComponent;
String featureType;
String value;
String comment;
String elementCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(int id)
{
this.id = id;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public String getUiComponent()
{
return uiComponent;
}
public void setUiComponent(String uiComponent)
{
this.uiComponent = uiComponent;
}
public String getFeatureType()
{
return featureType;
}
public void setFeatureType(String featureType)
{
this.featureType = featureType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getElementCode() {
return elementCode;
}
public void setElementCode(String elementCode) {
this.elementCode = elementCode;
}
}
But when i submitting the json request it is giving 415 unsuporrted media type error.
What is wrong with this code. Do anybody havve the answer. Thanks in advance.
Nothing with the code. You just need to make sure that Your POST request has the HTTP Content-Type header set to "application/json".
If you use curl to POST the data you can use the following parameter to set the header value:
curl -H "Content-Type:application/json"
Add an Accept header too:
curl -H "Content-Type:application/json" -H "Accept:application/json"

Is there a way to skip tests in base classes?

I'm using C# 4.0, Visual Studio 2010 and am annotating my methods/classes with the attributes from the Microsoft.VisualStudio.TestTools.UnitTesting namespace.
I'd like to use inheritance in my test classes where each additional inheritance represents something changing or being created. If I could get it to not run tests from the base classes, then everything would be fine. Here's a rough example:
public class Person
{
public int Energy { get; private set; }
public int AppleCount { get; private set; }
public Person()
{
this.Energy = 10;
this.AppleCount = 5;
}
public void EatApple()
{
this.Energy += 5;
this.AppleCount--;
}
}
[TestClass]
public class PersonTest
{
protected Person _person;
[TestInitialize]
public virtual void Initialize()
{
this._person = new Person();
}
[TestMethod]
public void PersonTestEnergy()
{
Assert.AreEqual(10, this._person.Energy);
}
[TestMethod]
public void PersonTestAppleCount()
{
Assert.AreEqual(5, this._person.AppleCount);
}
}
[TestClass]
public class PersonEatAppleTest : PersonTest
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
this._person.EatApple();
}
[TestMethod]
public void PersonEatAppleTestEnergy()
{
Assert.AreEqual(15, this._person.Energy);
}
[TestMethod]
public void PersonEatAppleTestAppleCount()
{
Assert.AreEqual(4, this._person.AppleCount);
}
}
I asked a coworker and he suggested separating the initializing code from the testing. Inherit all the setup code, but then place all the tests for a particular setup in a class that inherits from said setup code. So the above would become:
public class Person
{
public int Energy { get; private set; }
public int AppleCount { get; private set; }
public Person()
{
this.Energy = 10;
this.AppleCount = 5;
}
public void EatApple()
{
this.Energy += 5;
this.AppleCount--;
}
}
[TestClass]
public class PersonSetup
{
protected Person _person;
[TestInitialize]
public virtual void Initialize()
{
this._person = new Person();
}
}
[TestClass]
public class PersonTest : PersonSetup
{
[TestMethod]
public void PersonTestEnergy()
{
Assert.AreEqual(10, this._person.Energy);
}
[TestMethod]
public void PersonTestAppleCount()
{
Assert.AreEqual(5, this._person.AppleCount);
}
}
[TestClass]
public class PersonEatAppleSetup : PersonSetup
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
this._person.EatApple();
}
}
[TestClass]
public class PersonEatAppleTest : PersonEatAppleSetup
{
[TestMethod]
public void PersonEatAppleTestEnergy()
{
Assert.AreEqual(15, this._person.Energy);
}
[TestMethod]
public void PersonEatAppleTestAppleCount()
{
Assert.AreEqual(4, this._person.AppleCount);
}
}
If someone else knows how to skip inherited methods like I originally asked, then I'll accept that. If not, then eventually I'll accept this answer.

Castle Windsor Typed Factory Facility

When _fwf.GetFileWatcher is called, always MailWatcher is returning. How can I return FileWatcher class with typed factory facility? I tried code block as below but this gets always the first component.
Also I tried DefaultTypedFactoryComponentSelector but i can't get a result.
public interface IWatcher : IDisposable
{
void StartWatching();
}
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory(x => x.SelectedWith(new FileWatcherSelector())));
_fwf = _container.Resolve<IFileWatcherFactory>();
strong textvar fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For anyone looking at this, using the TypedFactoryFacility, to dictate which type the Factory will create if this varies, you can use the Get[Name] convention, where your interface will have a create method for each implementation type.
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetMailWatcher(string path);
IWatcher GetFileWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().Named("MailWatcher").LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().Named("FileWatcher").LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory());
_fwf = _container.Resolve<IFileWatcherFactory>();
var fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For more information, please refer to :
http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx#Get_methods_lookup_components_by_name_4