Test case for constructor as i have a filter logic - tdd

I have constructor where there is filter logic and wanna test it, though writing test case for constructor is not in practice i wanna have the code coverage , have tried many links but none are explaining about handling a constructor.
public Myclass {
public Myclass(AnotherClass obj)
{
_key = obj.key;
_ID = obj.ID;
_CandidateMode = obj.CandidateMode;
if(_CandidateMode == obj.CandidateMode.numeric
{
//Dosomething
}
else
{
//Do something with special character.
}
}
}

Definitely placing logic inside a constructor is a thing to avoid. Good you know that :-) In this particular case maybe the if could go into each of the public methods of MyClass, or maybe you could use polymorphism (create MyClass or MySpecialCharacterClass base on the AnotherClass object)?
Anyway, to get to a straight answer: if you really must test constructor logic, do it like you would test any other method (in some languages it's just a static method called new, by the way).
[TestMethod]
public void is_constructed_with_numeric_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.numeric };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for numeric candidate
...
}
[TestMethod]
public void is_constructed_with_special_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.special };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for special candidate
...
}

Related

Unity C# Error: 'Sprite' does not contain a constructor that takes 0 arguments

I've been working on an item system for my game in Unity. I am still pretty new to coding, but I am giving it my best effort.
My Item system Works by accessing interfaces with the data I need. While trying to assign my sprite from the interface to a private variable, I get the error "'Sprite' does not contain a constructor that takes 0 arguments." I have looked all over for solutions, and haven't found any fixes that have worked for me so far.
The Class I created to access the interface looks like this:
public class ISType : IISType {
[SerializeField] string _name;
[SerializeField] Sprite _icon;
ISType()
{
_name = "Type";
_icon = new Sprite(); }
public string Name
{
get
{ return _name; }
set
{ _name = value }
}
public Sprite Icon {
get
{ return _icon; }
set
{ _icon = value; }
}
}
If anyone can tell what is going on I would really appreciate the help! :)
It looks like Sprite does not contain a public constructor accepting zero arguments.
A class with no constructors defined will have a parameterless constructor.
public class MyClass { }
MyClass x= new MyClass(); // this is valid
However if it has any other constructors defined, this parameterless 'default' constructor is no longer 'a given'.
Difference between default constructor and paramterless constructor?
Answer by Nicole Calinoiu
The "default" constructor is added by the C# compiler if your class does not contain an explicit instance constructor. It is a public, parameterless constructor.
https://stackoverflow.com/a/10498709/5569485
public class MyClass {
public MyClass(string foo)
{
}
}
MyClass x= new MyClass(); // this is invalid
The class would have to manually define a parameterless constructor.
public class MyClass {
// parameterless constructor
public MyClass()
{
}
public MyClass(string foo)
{
}
}
MyClass x= new MyClass(); // this is valid again!
Sometimes no constructors are provided publicly, and a class instead provides static methods to instantiate the object.
public class MyClass
{
private MyClass()
{
}
public static MyClass Create()
{
return new MyClass();
}
}
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
Without knowing more about the Sprite class, my guess is that there is a static method for creating instances of the Sprite
something like
Sprite sprite = Sprite.Create(...);
The answer is in the error. There is no constructor that takes 0 parameters for Sprite. Without seeing the code I'm guessing you made a custom constructor with parameters and didn't add a paramaterless one.
A default parameterless constructor would look like:
Sprite()
{}
Be sure to do a lot more reading and tutorials. This is fairly basic class information.

overwrite xor in groovy

I am looking for an way to overwrite xor on an groovy script.
I've created a base class for my script where a Object is defined. This object already has a method public Object xor(String var) which works like myobject^"foo". What I want is way to access this method like myobject^foo where foo handled like a normal String.
as i understand you want to do somehow that
(myobject^"foo") == (myobject^foo)
so, in your script you can redefine method getProperty() so in your script access to foo property will return "foo" string..
class A{
public Object xor(Object o){
println "xor $o"
return o
}
}
public getProperty(String key){
if(key in ['out'])return super.getProperty(key) //skip standard properties
return key
}
def myobject=new A()
assert (myobject^foo) == (myobject^"foo")
but i don't see any benefits :)
Based on your answer #daggett I found a method which handles missing properties:
public abstract class MyBaseScript extends Script implements GroovyObject {
protected class A {
public Object xor(String var) {
//do fancy stuff
return var;
}
}
protected A foo = new A();
//method which handles missing properties
public Object propertyMissing(String name) {
return name;
}
}
How do I start my scripts:
Binding binding = new Binding();
// passing parameters
binding.setVariable("arg0", arg0);
binding.setVariable("args", arg1);
// Compiler Config
CompilerConfiguration cc = new CompilerConfiguration();
ImportCustomizer ic = new ImportCustomizer();
// add some imports for e.g.
ic.addImports("java.awt.Color", "java.util.Calendar",...);
cc.addCompilationCustomizers(ic);
// set BaseClass
cc.setScriptBaseClass("de.MyBaseScript");
// execute script
GroovyClassLoader loader = new GroovyClassLoader();
shell = new GroovyShell(loader, binding, cc);
Script gscript = shell.parse(groovyScriptAsAFile);
Object o = gscript.run();

Java - Generic class extended by concrete class

I have a number of classes, POJO style, that shares a single functionality, say readCSV method. So I want to use a single parent (or maybe abstract, not sure if it should be) class that these POJOs can extend. Here's a pseudo-code:
(abstract) class CSVUtil {
private String[] fileHeader = null;
protected void setFileHeader(fileHeader) {
this.fileHeader = fileHeader;
}
protected List<WhateverChildClass> readCSV(String fileName) {
// read CSV using Apache Commons CSV
// and return a List of child type
List<WhateverChildClass> list = null;
// some declarations
try {
list = new ArrayList<WhateverChildClass>();
csvParser = new CSVParser(fileReader, csvFormat);
List csvRecords = csvParser.getRecords();
for (...) {
CSVRecord record = (CSVRecord) csvRecords.get(i);
WhateverChildClass childClass = new WhateverChildClass();
// loop through fields of childClass using reflection and assign
for (// all fields of childClass) {
childClass.setWhateverField(record.get(fileHeader[i]));
}
list.add(childClass);
System.out.println(p);
ps.add(p);
}
}
...
return list;
}
}
on one of the child classes, say ChildA
class ChildA extends CSVUtil {
// fields, getters, setters
}
How do I code the CSVUtil such that I can determine in runtime the child class in readCSV defined in the parent class?
Is it possible to make this method static and still be inherited?
As an alternative, is there API in Apache Commons CSV that can generally read a CSV, determine its schema, and wrap it as a generic Object (I don't know if I make sense here), and return a list of whatever that Object is ?
You want that readCSV to be a static method ?
Then, i would say that ChildA class shouldn't inherit from CSVUtil, but implement an Interface ... something like that :
public final class CSVUtil {
private CSVUtil() {
}
public static <T extends ICSV> List<T> readCSV(String filename) {
...
}
class ChildA implements ICSV

How do I make my Entity Framework based Repository Class LINQ friendly?

How can I use LINQ if I have wrapped my Entity Framework data context with a Repository class?
I want to do something like:
class A
{
public IRepositiry<T> GetRepository<T>()
{
DbContextAdapter adapter = new DbContextAdapter(ctx);
return new Repository<T>(adapter);
}
}
class B
{
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
// Do some linq queries here, don't know how.
rep.[get Linqu] (from ...);
}
}
To keep your repository LINQ friendly you need to have some methods or properties on it that return IQueryable<T> or IEnumerable<T>
So in class Repository<T> you would have a method like this:
public class Repository<T>
{
DbContextAdapter ctx;
// other methods omitted
IEnumerable<Houses> GetHouses()
{
return ctx.Houses
}
}
Then in DoSomething you could do this:
void DoSomething()
{
A a = new A();
IRepository<House> rep = a.GetRepository<House>();
var q = from house in rep.GetHouses()
where house.Color = "Purple"
select house;
foreach(var h in q)
{
house.SetOnFire();
}
}
The standard query operators allow queries to be applied to any
IEnumerable-based information source. - MSDN
As long as you write methods that return IEnumerable Collections you will be compatible with LINQ.
at the risk of been completely lazy, what you want to implement is known as the repository pattern, check out Huyrya as its a good article.
Also it's possible to extend the entity classes, so they return instances or lists of themselves (singleton pattern). Aka:
public partial class FOO : FOO
{
public IEnumerable<Foo> GetFooList()
{
using (var context = new FooEntities())
{
return // YOU CODE TO GET LIST OF FOO
}
}
}
Or something like that (code syntax is not right but should give you the general idea). If your entity classes are going to implement similar methods, abstract them into interface contract and get your partial entity classes to implement that interface.

Visual Studio code generated when choosing to explicitly implement interface

Sorry for the vague title, but I'm not sure what this is called.
Say I add IDisposable to my class, Visual Studio can create the method stub for me. But it creates the stub like:
void IDisposable.Dispose()
I don't follow what this syntax is doing. Why do it like this instead of public void Dispose()?
And with the first syntax, I couldn't work out how to call Dispose() from within my class (in my destructor).
When you implement an interface member explicitly, which is what the generated code is doing, you can't access the member through the class instance. Instead you have to call it through an instance of the interface. For example:
class MyClass : IDisposable
{
void IDisposable.Dispose()
{
// Do Stuff
}
~MyClass()
{
IDisposable me = (IDisposable)this;
me.Dispose();
}
}
This enables you to implement two interfaces with a member of the same name and explicitly call either member independently.
interface IExplict1
{
string InterfaceName();
}
interface IExplict2
{
string InterfaceName();
}
class MyClass : IExplict1, IExplict2
{
string IExplict1.InterfaceName()
{
return "IExplicit1";
}
string IExplict2.InterfaceName()
{
return "IExplicit2";
}
}
public static void Main()
{
MyClass myInstance = new MyClass();
Console.WriteLine( ((IExplcit1)myInstance).InstanceName() ); // outputs "IExplicit1"
IExplicit2 myExplicit2Instance = (IExplicit2)myInstance;
Console.WriteLine( myExplicit2Instance.InstanceName() ); // outputs "IExplicit2"
}
Visual studio gives you two options:
Implement
Implement explicit
You normally choose the first one (non-explicit): which gives you the behaviour you want.
The "explicit" option is useful if you inherit the same method from two different interfaces, i.e multiple inheritance (which isn't usually).
Members of an interface type are always public. Which requires their method implementation to be public as well. This doesn't compile for example:
interface IFoo { void Bar(); }
class Baz : IFoo {
private void Bar() { } // CS0737
}
Explicit interface implementation provides a syntax that allows the method to be private:
class Baz : IFoo {
void IFoo.Bar() { } // No error
}
A classic use for this is to hide the implementation of a base interface type. IEnumerable<> would be a very good example:
class Baz : IEnumerable<Foo> {
public IEnumerator<Foo> GetEnumerator() {}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { }
}
Note how the generic version is accessible, the non-generic version is hidden. That both discourages its use and avoids a compile error because of a duplicate method.
In your case, implementing Dispose() explicitly is wrong. You wrote Dispose() to allow the client code to call it, forcing it to cast to IDisposable to make the call doesn't make sense.
Also, calling Dispose() from a finalizer is a code smell. The standard pattern is to add a protected Dispose(bool disposing) method to your class.

Resources