I am trying to write test case but stuck with this error. How to fix this error ?
#Override
public boolean isDuplicateSystemDetail(SystemFormBean systemFormBean){
List<BrmSystem> list = systemDao.isDuplicateSystemDetail(systemFormBean);
if(CollectionUtils.isNotEmpty(list)){
return true;
}else{
return false;
}
}
---------------------------------------------------------------------------
#Test
public void isDuplicateSystemDetail_Should_Return_True(){
List<BrmSystem> list = new ArrayList<BrmSystem>();
BrmSystem brmSystem = new BrmSystem();
SystemFormBean systemFormBean = new SystemFormBean();
brmSystem.setSystemName("Test");
list.add(brmSystem);
when(systemDao.isDuplicateSystemDetail(systemFormBean)).thenReturn(list);
}
Probably SystemFormBean class doesn't override equals(). So when isDuplicateSystemDetail(systemFormBean) invokes, it has another object of this class as a parameter which is not the same as the one you've created manually (by default Object.equals() compares memory adresses which would be false in your case).
Try to override equals() to compare by f.e. actual fields of SystemFormBean or rewrite "when" clause as
systemDao.isDuplicateSystemDetail(Mockito.any(SystemFormBean.class))
Related
I have some code that returns Mono<List<UserObject>>. The first thing I want to do is check the List is not empty, and if it is, throw a NoUsersFoundException. My code looks like this:
IUserDao.java
Mono<List<UserAccount>> getUserProfiles(final Set<UserQueryFilter> filters,
final Set<String> attributes);
GetUserAccount.java
public Mono<UserAccount> doGetUserAccount() {
return userDao.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
throw new NoUsersFoundException();
}
return list;
})
.map(this::removePermissions)
.map(this::removeDuplicates);
}
I want to write a unit test that will test that the NoUsersFoundException is thrown when userDao.getUserProfiles(filters, attributes) returns an empty list. When I use Mockito#when with a .thenReturn(), the test will, as expected, return immediately once userDao.getUserProfiles(...) is called without continuing the flow into the .map() where the list is checked and exception thrown.
#Mock
private IUserDao userDao;
private UserPolicies userPolicies;
#BeforeEach
public void init() {
userPolicies = new UserPolicies(Set.of("XYZ", USER_AFF, "123"),
Set.of(TestUserConstants.ID, TestUserConstants.SUBSCRIPTION_LEVEL));
}
#Test
void shouldThrowExceptionIfNoUsersFound() {
final Set<UserFilter> filters = new UserFilterBuilder().withId(ID)
.withSubscription(PREMIUM)
.build();
when(userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenReturn(Mono.just(Collections.emptyList()));
testClass = new GetUserAccount(userDao,
userPolicies,
filters,
userPolicies.getUserAttributeIds());
assertThatThrownBy(() -> testClass.doGetUserAccount()).isInstanceOf(NoUsersFoundException.class);
}
I have tried .thenAnswer() but it essentially does the same thing as the method called is not a void:
userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenAnswer((Answer<Mono<List>>) invocationOnMock -> Mono.just(Collections.emptyList()));
I can't see how using reactor.test.StepVerifier would work for this case.
i dont really understand what you are asking for, but we commonly dont "throw" exceptions in reactor. We return a Mono#error downstream, and different operators will react accordingly as the error travels downstream.
public Mono<List<Foobar> fooBar(filters, attributes) {
return daoObject.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
// Return a mono#error
return Mono.error( ... );
}
return list;
})
}
And then test using the step verifier. With either expectNext or expectError.
// Happy case
StepVerifier.create(
fooBar(filters, attributes))
.expectNext( ... )
.verify();
// Sad case
StepVerifier.create(
fooBar(filters, attributes))
.expectError( ... )
.verify();
The JSON returned when a REST request is made all works great except any bool property, if false, does not get included in the JSON (verified via Fiddler). I tried:
[DataMember(IsRequired = true)]
public bool success { get; set; }
but it still didn't return it.
Any suggestions? And I do like that it doesn't return anything for nulls, it's just bools that I want always returned.
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.IgnoreAndPopulate;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}
}
DatasourceController.cs:
public class DatasourceController : ApiController
{
[HttpGet("datasource/metadata/{datasource}")]
public MetaDataInfo GetDatasourceSchema(string datasource, string node = "")
{
DocumentInfo docInfo = DocumentData.GetDocInfo("dave");
return MetaDataFactory.GetMetaDataInfo(docInfo, datasource, node);
}
}
I was looking for the same information.
It turns out you can specify for a specific property using:
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
I've tested on ASP.NET Core 1 RC2.
That's MVC 6.
I think that by putting the [DefaultValue(false)] attribute above your success variable and other bool variables you should get your desired result.
You have set DefaultValueHandling to Newtonsoft.Json.DefaultValueHandling.IgnoreAndPopulate. From the documentation we can read:
Ignore members where the member value is the same as the member's default value when serializing objects and sets members to their default value when deserializing.
As I read that it means that during serializing your false boolean values should disappear. However, as long as it has a default value it will appear in the JSON again when you deserialize.
How would I write a simple LINQ to SQL extension method called "IsActive" which would contain a few basic criteria checks of a few different fields, so that I could reuse this "IsActive" logic all over the place without duplicating the logic.
For example, I would like to be able to do something like this:
return db.Listings.Where(x => x.IsActive())
And IsActive would be something like:
public bool IsActive(Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
Otherwise, I am going to have to duplicate the same old where criteria in a million different queries right throughout my system.
Note: method must render in SQL..
Good question, there is a clear need to be able to define a re-useable filtering expression to avoid redundantly specifying logic in disparate queries.
This method will generate a filter you can pass to the Where method.
public Expression<Func<Listing, bool>> GetActiveFilter()
{
return someListing => someListing.Approved && !someListing.Deleted;
}
Then later, call it by:
Expression<Func<Filter, bool>> filter = GetActiveFilter()
return db.Listings.Where(filter);
Since an Expression<Func<T, bool>> is used, there will be no problem translating to sql.
Here's an extra way to do this:
public static IQueryable<Filter> FilterToActive(this IQueryable<Filter> source)
{
var filter = GetActiveFilter()
return source.Where(filter);
}
Then later,
return db.Listings.FilterToActive();
You can use a partial class to achieve this.
In a new file place the following:
namespace Namespace.Of.Your.Linq.Classes
{
public partial class Listing
{
public bool IsActive()
{
if(this.Approved==true && this.Deleted==false)
return true;
else
return false;
}
}
}
Since the Listing object (x in your lambda) is just an object, and Linq to SQL defines the generated classes as partial, you can add functionality (properties, methods, etc) to the generated classes using partial classes.
I don't believe the above will be rendered into the SQL query. If you want to do all the logic in the SQL Query, I would recommend making a method that calls the where method and just calling that when necessary.
EDIT
Example:
public static class DataManager
{
public static IEnumerable<Listing> GetActiveListings()
{
using (MyLinqToSqlDataContext ctx = new MyLinqToSqlDataContext())
{
return ctx.Listings.Where(x => x.Approved && !x.Deleted);
}
}
}
Now, whenever you want to get all the Active Listings, just call DataManager.GetActiveListings()
public static class ExtensionMethods
{
public static bool IsActive( this Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
}
Late to the party here, but yet another way to do it that I use is:
public static IQueryable<Listing> GetActiveListings(IQueryable<Listing> listings)
{
return listings.Where(x => x.Approved && !x.Deleted);
}
and then
var activeListings = GetActiveListings(ctx.Listings);
In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were
private to the instance and not the
class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
public class Example {
private int a;
public int getOtherA(Example other) {
return other.a;
}
}
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful.
If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
Here's the equivalent of Michael Borgwardt's answer for when you are not able to access the private fields of the other object:
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return other.valueEquals(this.value); // <------------
}
#Override // This method would probably also be declared in an interface
public boolean valueEquals(int oValue) {
return this.value == oValue;
}
}
Nowadays this is familiar to Ruby programmers but I have been doing this in Java for a while. I prefer not to rely on access to another object's private fields. Remember that the other object may belong to a subclass, which could store the value in a different object field, or in a file or database etc.
Example code (Java):
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return this.value == other.value; // <------------
}
}
If the assumption "private member variables are private to the instance" were correct, the marked line would cause a compiler error, because the other.value field is private and part of a different object than the one whose equals() method is being called.
But since in Java (and most other languages that have the visibility concept) private visibility is per-class, access to the field is allowed to all code of the MutableInteger, irrelevant of what instance was used to invoke it.
I just started using LINQ to SQL classes, and really like how this helps me write readable code.
In the documentation, typical examples state that to do custom validation, you create a partial class as so::
partial class Customer
{
partial void OnCustomerIDChanging(string value)
{
if (value=="BADVALUE") throw new NotImplementedException("CustomerID Invalid");
}
}
And similarly for other fields...
And then in the codebehind, i put something like this to display the error message and keep the user on same page so to correct the mistake.
public void CustomerListView_OnItemInserted(object sender, ListViewInsertedEventArgs e)
{
string errorString = "";
if (e.Exception != null)
{
e.KeepInInsertMode = true;
errorString += e.Exception.Message;
e.ExceptionHandled = true;
}
else errorString += "Successfully inserted Customer Data" + "\n";
errorMessage.Text = errorString;
}
Okay, that's easy, but then it stops validating the rest of the fields as soon as the first Exception is thrown!! Mean if the user made mode than one mistake, she/he/it will only be notified of the first error.
Is there another way to check all the input and show the errors in each ?
Any suggestions appreciated, thanks.
This looks like a job for the Enterprise Library Validation Application Block (VAB). VAB has been designed to return all errors. Besides this, it doesn't thrown an exception, so you can simply ask it to validate the type for you.
When you decide to use the VAB, I advise you to -not- use the OnXXXChanging and OnValidate methods of LINQ to SQL. It's best to override the SubmitChange(ConflictMode) method on the DataContext class to call into VAB's validation API. This keeps your validation logic out of your business entities, which keeps your entities clean.
Look at the following example:
public partial class NorthwindDataContext
{
public ValidationResult[] Validate()
{
return invalidResults = (
from entity in this.GetChangedEntities()
let type = entity.GetType()
let validator = ValidationFactory.CreateValidator(type)
let results = validator.Validate(entity)
where !results.IsValid
from result in results
select result).ToArray();
}
public override void SubmitChanges(ConflictMode failureMode)
{
ValidationResult[] this.Validate();
if (invalidResults.Length > 0)
{
// You should define this exception type
throw new ValidationException(invalidResults);
}
base.SubmitChanges(failureMode);
}
private IEnumerable<object> GetChangedEntities()
{
ChangeSet changes = this.GetChangeSet();
return changes.Inserts.Concat(changes.Updates);
}
}
[Serializable]
public class ValidationException : Exception
{
public ValidationException(IEnumerable<ValidationResult> results)
: base("There are validation errors.")
{
this.Results = new ReadOnlyCollection<ValidationResult>(
results.ToArray());
}
public ReadOnlyCollection<ValidationResult> Results
{
get; private set;
}
}
Calling the Validate() method will return a collection of all errors, but rather than calling Validate(), I'd simply call SubmitChanges() when you're ready to persist. SubmitChanges() will now check for errors and throw an exception when one of the entities is invalid. Because the list of errors is sent to the ValidationException, you can iterate over the errors higher up the call stack, and present them to the user, as follows:
try
{
db.SubmitChanges();
}
catch (ValidationException vex)
{
ShowErrors(vex.ValidationErrors);
}
private static void ShowErrors(IEnumerable<ValidationResult> errors)
{
foreach(var error in errors)
{
Console.WriteLine("{0}: {1}", error.Key, error.message);
}
}
When you use this approach you make sure that your entities are always validated before saving them to the database
Here is a good article that explains how to integrate VAB with LINQ to SQL. You should definitely read it if you want to use VAB with LINQ to SQL.
Not with LINQ. Presumably you would validate the input before giving it to LINQ.
What you're seeing is natural behaviour with exceptions.
I figured it out. Instead of throwing an exception at first failed validation, i store an error message in a class with static variable. to do this, i extend the DataContext class like this::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for SalesClassesDataContext
/// </summary>
public partial class SalesClassesDataContext
{
public class ErrorBox
{
private static List<string> Messages = new List<string>();
public void addMessage(string message)
{
Messages.Add(message);
}
public List<string> getMessages()
{
return Messages;
}
}
}
in the classes corresponding to each table, i would inherit the newly defined class like this::
public partial class Customer : SalesClassesDataContext.ErrorBox
only in the function OnValidate i would throw an exception in case the number of errors is not 0. Hence not attempting to insert, and keeping the user on same input page, without loosing the data they entered.