I have the following code:
class classA {
constructor() {
createjs.EventDispatcher.initialize(classA.prototype);
this.addEventListener("someEvent", function(evt) {
console.log("classA has detected something has happened!");
});
}
}
class classB {
constructor() {
createjs.EventDispatcher.initialize(classB.prototype);
this.addEventListener("someEvent", function(evt) {
console.log("classB has detected something has happened!");
});
this.dispatchEvent("someEvent");
}
}
let a = new classA();
let b = new classB();
Now when I construct classA it is set to listen for "someEvent", however when "someEvent" is dispatched in the constructor of classB only classB registers the event.
Why is this?
This is happening because only "ClassB" instances are listening for an event dispatched by "ClassB" instances. When you create your classes, you are:
Mixing in the EventDispatcher
Adding a listener to this for "someEvent"
And then (only) the ClassB instance is dispatching "someEvent".
ClassA instances will not catch events dispatched by ClassB instances, because each class is only listening for events on themselves.
If you want to catch events from ClassB, you would have to set it up to do that.
var a = new ClassA();
var b = new ClassB();
b.addEventListener("someEvent", a.someFunction);
Note also that you are mixing in the EventDispatcher to the prototype in the constructor. If you want it in the prototype, add it outside the constructor -- otherwise it happens each time. If you want it just on the one instance, then put it in the constructor, but just pass this instead of Class.prototype.
class ClassB {
// stuff
}
createjs.EventDispatcher.initialize(ClassB.prototype);
Or better, just extend EventDispatcher.
Class B extends createjs.EventDispatcher {
// stuff
}
Related
Given below is the structure of my project
class A{
void methodA(){
// Gets data from the DB
// Processes the data
// Sends the data via a kafka topic MyTopic
kafka.send(topicName, data);
}
}
class B{
// methodB is listening to topic MyTopic
void methodB(String data){
}
}
I want to test this entire flow.
Using Mockito, is there a way to call methodB directly (bypassing kafka) when kafka.send is triggered in methodA?
Not sure that I am understanding what you have mocked and what not but my approach would look like this:
#InjectMocks
private ClassA classA;
#Mock
Kafka kafka
private String data = "someData";
private String topicName = "someTopicName";
#Test
void yourTestMethod() {
B objectOfClassB = new B();
when(kafka.send(any(), any()).thenAnswer(a -> {
CustomObject data = (CustomObject) a.getArguments()[1]; // get the Data object
objectOfClassB.MethodB(data);
return;
});
classA.methodA();
Assertions.assertThat(objectOfClassB.getSomeAssertionValue()).isEqualTo(1);
}
ObjectB can obiously be a service spy or something else. It does not have to be instantiated by "new". Any Object reference given will do the trick.
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.
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
...
}
I have code like this...
#Validateable
class RecipientsCommand {
...
EmailService emailService
void getEmailEligibleRecipients(Long accountId){
emailService.loadEligibleEmail(accountId)
}
}
resource.groovy
imports com.test.commands.RecipientsCommand
beans = {
recipientsCommand(RecipientsCommand){bean -> bean.autowire = true}
}
But the service is still always null when I call
new RecipientCommand()
Since the Command Object seems to be an interface between the views and the controller I am creating it, filling it and passing it to the view. Then I am using it to parse and save data. If I change to...
EmailService emailService = new EmailService()
Everything works fine.
The auto wiring only happens when Grails creates the instance for you. You can't just new RecipientCommand() and expect Spring to be involved in that. If you retrieve the recipientsCommand bean from the Spring application context it will be auto wired and if the RecipientCommand is created by the framework and passed as an argument to your controller action, that will also be auto wired. invoking the new RecipientCommand() constructor will result in a new instance being created which is not auto wired.
EDIT:
Examples...
class SomeController {
def someAction(RecipientCommand co) {
// co will already be auto wired
// this approach does NOT require you to have defined the
// recipientsCommand bean in resources.groovy
}
}
class SomeOtherController {
def someAction() {
// rc will be autowired
// this approach requires you to have defined the
// recipientsCommand bean in resources.groovy
def rc = grailsApplication.mainContext.getBean('recipientsCommand')
}
}
class AnotherSomeOtherController {
def recipientsCommand
def someAction() {
// recipientsCommand will be auto wired
// this approach requires you to have defined the
// recipientsCommand bean in resources.groovy
}
}
class YetAnotherController {
def someAction() {
// rc will not be autowired
def rc = new RecipientCommand()
}
}
I hope that helps.
I've got the following code
public delegate void NotificacaoScanner(NotifScanner e);
// interface
public interface IScanner
{
event NotificacaoScanner onFinalLeitura;
}
// abstract class that implements the interface
public abstract class ScannerGCPerif : IScanner
{
public virtual event NotificacaoScanner onFinalLeitura;
{
add { throw new NotImplementedException("Event not available for this service"); }
remove { throw new NotImplementedException("Event not available for this service"); }
}
}
// concrete class that implements the abstract class
public class ScannerBurroughs : ScannerGCPerif
{
public override event NotificacaoScanner onFinalLeitura;
}
Why when I subscribe the onFinalLeitura event of a ScannerBurroughs instance, it insists on execute the event declaration of the base class (ScannerGCPerif), where the exception is?
I ran your code and I did not get an exception. Let me explain what happens:
You override the event in your concrete class, but you do not provide implementation for adding and removing event handlers so the compiler generates the following code:
public class ScannerBurroughs : ScannerGCPerif
{
private NotificacaoScanner _onFinalLeitura; // Declare a private delegate
public override event NotificacaoScanner onFinalLeitura
{
add { _onFinalLeitura += value; }
remove { _onFinalLeitura -= value; }
}
}
Behind the scenes it adds a private delegate and autoimplements the add / remove event accessors. The base implementation never gets called when you subscribe. Try explicitly implementing the accessors, put some breakpoints in your code and see what happens.