How to test an add to list method with JUnit - eclipse

I'm trying to test my add to list method using JUnit.
Here is my test method:
public int urunEkleTest(String marka, String urun) {
UrunDepo depo = new UrunDepo();
String urunekle = depo.urunEkle("Iphone","Apple");
But I have a error message with this test method
Error msg = The method urunEkle(Urun) in the type UrunDepo is not applicable for the arguments (String, String)
And my add to list method is :
public static List<Urun> urunEkle(Urun urun){
URUNLER.add(urun);
return URUNLER;
}

You call a method with one parameter with two parameters.

Related

Entity Framework execute stored procedure with params

Ok, hope to not get too many flags, but it's to annoying.
I have a method in my controller which calls a method from another class:
offerForCreate.Rating = CalculateRating.CreateRating(addOffer);
and entire called class :
public class CalculateRating
{
private readonly DataContext mainContext;
public CalculateRating(DataContext mainContext)
{
this.mainContext = mainContext;
}
// calcul rating oferte noi
public decimal CreateRating(OfferForCreate offer)
{
decimal rating = mainContext.Database.FromSql<decimal>("RatingCalculator", offer.locationId, offer.typeId);
return rating;
}
}
I get an error when try to execute this procedure:
Error CS1061: 'DatabaseFacade' does not contain a definition for 'FromSql' and no extension method 'FromSql' accepting a first argument of type 'DatabaseFacade' could be found
and another if I don't create an instance of CalculateRating class in my controller :
Controllers\AnnouncesController.cs(127,37): error CS0120: An object reference is required for the non-static field, method, or property 'CalculateRating.CreateRating(OfferForCreate)
Everywhere I see must specify the entity, but what entity I can specify if my stored procedure use multiple tables?
Asp.Net Core Web API
You can execute stored proc like this:
using (var command = mainContext.Database.GetDbConnection().CreateCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "dbo.RatingCalculator";
var locationIdParam = new System.Data.SqlClient.SqlParameter("#locationId", System.Data.SqlDbType.Int);
locationIdParam .Value = offer.locationId;
//DO same for typeId parameter
//Params to Parameters collection
command.Parameters.Add(locationIdParam);
command.Connection.Open();
return (double)command.ExecuteScalar();
}
Controllers\AnnouncesController.cs(127,37): error CS0120: An object reference is required for the non-static field, method, or property 'CalculateRating.CreateRating(OfferForCreate)
This error is occuring because if you declare CalculateRating as static you can not reference in non-static field mainContext.
You should create an instance of your CalculateRating class using Dependency Injection. Here are steps:
Create an interface ICalculateRating
public interface ICalculateRating {
decimal CreateRating(OfferForCreate offer);
}
Update CalculateRating class to implement ICalculateRating
Register the DBContext and ICalculateRating mappings in ConfigureServices method of Startup.cs file like this:
services.AddDbContext<DbContext>(opts=> { opts.UseSqlServer("sqlserver conntection string") }, ServiceLifetime.Scoped);
services.AddTransient<ICalculateRating, CalculateRating>();
In your controller constructor, input an argument of type ICalculateRating which will be injected by Microsoft Dependency Injection framework at runtime:
private readonly ICalculateRating _calculateRating;
public MyController(ICalculateRating calculateRating) {
_calculateRating = calculateRating;
}
You can then call the method like this:
offerForCreate.Rating = _calculateRating.CreateRating(addOffer);

vertx 2: vertx.eventBus().send(ClassName.ADDRESS, ....) why does it init a new class?

I work on a project based on Vertx the following line:
vertx.eventBus().send(MyClass.ADDRESS, requestBody, new Handler<Message<Object>>() {
....
}
public class MyClass implements Handler<Message<JsonObject>> {
public static final String ADDRESS = "coupons.api.manager";
...
#Override
public void handle(Message<JsonObject> msg) {
...
}
}
Whereas MyClass.ADDRESS is a static field of type string in the class MyClass, I found out that the line vertx.eventBus(...) creates an object of MyClass and then runs the handle() function.
My question is why? MyClass.ADDRESS is a string, and a static one. How does vertx "know" that it has to create an object from a class that this string is an attribute of?
I looked at the documentation of the send() function: http://vertx.io/docs/apidocs/io/vertx/core/eventbus/EventBus.html#send-java.lang.String-java.lang.Object-io.vertx.core.eventbus.DeliveryOptions-io.vertx.core.Handler-
and it says that the first argument in the function is "the address to send it to". OK. But, who said that the address means instantiating this class?
I made a small research, and yes. Vertx, behind the curtains, connects all the classes that implement Handler> to the string value they have in the attribute ClassName.ADDRESS.
When the statement:
vertx.eventBus().send(MyClass.ADDRESS, requestBody, new Handler<Message<Object>>() {
....
}
is invoked, a new thread is created and runs the handle method in the class MyClass.

Replace Anonymous Inner Class By Lambda. How does this work?

While sending a SOAP message, i wanted to add some custom headers so i did like below;
JAXBElement<ConfigurationResponse> jaxbElementResponse = (JAXBElement<ConfigurationResponse>) getWebServiceTemplate()
.marshalSendAndReceive(urlToSend,
new ObjectFactory().createConfigurationRequest(request),
new WebServiceMessageCallback() {
#Override
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
SaajSoapMessage soapMessage = (SaajSoapMessage) message;
SoapHeaderElement id = soapMessage.getSoapHeader().addHeaderElement(new QName(uri, localpart, prefix));
id.setText(text);
}
});
But "NetBeans" tell me i can use lambda expr. So if i do the change, it is like,
JAXBElement<ConfigurationResponse> jaxbElementResponse = (JAXBElement<ConfigurationResponse>) getWebServiceTemplate()
.marshalSendAndReceive(urlToSend,
new ObjectFactory().createConfigurationRequest(request), (WebServiceMessage message) -> {
SaajSoapMessage soapMessage = (SaajSoapMessage) message;
SoapHeaderElement id = soapMessage.getSoapHeader().addHeaderElement(new QName(uri, localpart, prefix));
id.setText(text);
});
Are both same? If yes, how this works?
A Lambda expression is syntactical sugar over an anonymous class. A Lambda can be used where ever the type is an functional interface, which is an interface which declares only one abstract method. The Lambda expression provides the implementation of that single method.
For your case the WebServiceMessageCallback is a functional interface. It has the one abstract method: doWithMessage(...). The Lambda expression you created provides the implementation of that method.

Adding functionality to Grails restfulcontroller

I'm having a very simple restful controller, which looks like this:
class PersonController extends RestfulController<Person> {
static responseFormats = ['json', 'xml']
PersonController() {
super(Person)
}
}
However, now I want to add a search option to this. What is the Grails way of making this possible?
I thought of adding the following:
def search(Map params) {
println params
}
But that makes Grails (2.3) crash (| Error Fatal error during compilation org.apache.tools.ant.BuildException: Compilation Failed (Use --stacktrace to see the full trace)).
So what is the right way of adding this? I'm looking for some solution which I can call using http://localhost:8080/foo/person/search?q=erik
This is my UrlMappings:
static mappings = {
"/$controller/$action?/$id?(.${format})?"{
constraints {
// apply constraints here
}
}
"/rest/persons"(resources:'Person')
I've changed the above to:
def search() {
println params
}
And that doesn't give the compilation error anymore, but I still get this error:
TypeMismatchException occurred when processing request: [GET] /declaratie-web/rest/medicaties/search - parameters:
q: erik
Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String. Stacktrace follows:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class nl.Person. Expected: class java.lang.Long, got class java.lang.String
I also found out that it doesn't matter how I call the controller:
http://localhost:8080/foo/person/search?q=erik
http://localhost:8080/foo/person/search222?q=erik
http://localhost:8080/foo/person/search39839329?q=erik
All fails with the above error, so it seems my method is ignored (maybe caused by my URLmapping?)
You really aren't being RESTful by doing that. q should just be a parameter for the index action. You can override that method to include your functionality.
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def c = Person.createCriteria()
def results = c.list(params) {
//Your criteria here with params.q
}
respond results, model:[personCount: results.totalCount]
}
#james-kleeh solution is right, but you can do it more clean by override the listAllResources method which is called by index
#Override
protected List<Payment> listAllResources(Map params) {
Person.createCriteria().list(params) {
// Your criteria here with params.q
}
}

NUnit with Rhino Mocks exception: Why is it throwing this exception?

I'm getting an exception that really makes no sense to me whatsoever.
I have an Expect call for a method that takes 3 arguments into it: The types are called CallContext, IDal, and List.
NUnit throws me 2 exceptions: One for not expecting a method call that happened where the types are CallContext, System.Object, and List, and one for expecting a call that didn't happen where the types are the correct ones. The fun thing is that the only way to call the method is with the 3 types mentioned above. There is no method call with type object!
Here is the code:
private IDal mockDal;
private CallContext mockContext;
private IWorkbooksLogic mockWLogic;
private ICommercialSpaceLogic mockCLogic;
private CmWorkbook mockWorkbook;
private IList<Workbook> mockList;
private MockRepository mock;
private Random random;
[SetUp]
public void Setup() {
mock = new MockRepository();
random = new Random();
this.mockDal = mock.StrictMock<IDal>() as IDal;
this.mockContext = new CallContext();
this.mockWLogic = mock.StrictMock<IWorkbooksLogic>() as IWorkbooksLogic;
this.mockCLogic = mock.StrictMock<ICommercialSpaceLogic>() as ICommercialSpaceLogic;
this.mockWorkbook = new CmWorkbook();
this.mockList = mock.StrictMock<IList<Workbook>>() as IList<Workbook>;
}
[Test]
public void ShouldFailWhenCreateWorkbookFails() {
int randBudget = random.Next(50);
int randEntity = random.Next(50);
int randWork = random.Next(50);
WorkbookDefinitions work = new WorkbookDefinitions {
WorkbookDefinitionID = randWork
};
Budget budget = new Budget {
BudgetID = randBudget,
WorkbookDefinitions = new List<WorkbookDefinitions> { work },
};
CommercialProperty property = new CommercialProperty {
CommercialPropertyID = randEntity,
CMEntity = new CMEntity {
EntityBase = new EntityEntity { EntityCode = "random.Next(50)" }
}
};
CmWorkbook book = new CmWorkbook {
WorkbookName = String.Format("CM — {0}", property.CMEntity.EntityBase.EntityCode)
};
OperationResults results = new OperationResults();
this.mockList.Add(book);
using (mock.Record()) {
Expect.On(this.mockDal).Call(this.mockDal.GetObject<Budget, int>(randBudget)).Return(budget);
Expect.On(this.mockDal).Call(this.mockDal.GetObject<CommercialProperty, int>(randEntity)).Return(property);
Expect.On(this.mockWLogic).Call(this.mockWLogic.Create(this.mockContext, this.mockDal, this.mockList)).Return(null);
}
using (mock.Playback()) {
results = CmWorkbookLogic.CreateWorkbook(mockContext, mockDal, mockWLogic, mockCLogic, randBudget, randEntity);
}
Assert.IsFalse(results.AllSuccessful);
}
The method being called is: workbooksLogic.Create(context, dal, new List { workbook })
Here is the NUnit error:
ShouldFailWhenCreateWorkbookFails:
Rhino.Mocks.Exceptions.ExpectationViolationException : ICRUDBaseLogic`1.Create(CallContext, System.Object, System.Collections.Generic.List`1[Workbook]); Expected #0, Actual #1.
ICRUDBaseLogic`1.Create(CallContext, IDalProxy8768e63f86da4601993b4791c696ada6, System.Collections.Generic.List`1[Workbook]); Expected #1, Actual #0.
I have no idea what the heck is going on with this. Anyone have any ideas?
Rhino Mocks uses the overloaded Equals method to compare arguments of the expected invocation and the invocation that actually happened. Some of the objects you are supplying as arguments don't have Equals overloaded (i.e. List class, not sure about the others), so the only way it would work if the supplied arguments had the same references (so were the same objects) as the ones you used to set up the expectation.
You have a few options:
Use IgnoreArguments, so that arguments will not be checked at all
Provide your own constraints, so that you can check if the arguments are what you expect them to be, but without using Equals()
Make sure these are exactly the same objects (if possible)