I can't cast this please help, It is the same class name with android view.View and com.stfalcon, but I can't change the class name to any of those because it is READ_ONLY_file, how can I cast this? I need to cast this >>>>> this.messagesList = (MessagesList) findViewById(R.id.messagesList);
this is my dependency, and I already import it from my DefaultMessagesActivity.java
implementation 'com.github.stfalcon:chatkit:0.3.3'
This is my Java
public class DefaultMessagesActivity extends DemoMessagesActivity
implements MessageInput.InputListener,
MessageInput.AttachmentsListener,
MessageInput.TypingListener{
public DefaultMessagesActivity(MessagesList messagesList){
}
public static void open(Context context) {
context.startActivity(new Intent(context, DefaultMessagesActivity.class));
}
private MessagesList messagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default_messages);
this.messagesList = (MessagesList) findViewById(R.id.messagesList); //ERROR HERE CANT CAST
This is my xml file name activity_default_messages.xml
<com.stfalcon.chatkit.messages.MessagesList
android:id="#+id/messagesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/input"/>
You are doing similar error like you did here. same class name with android view.View and com.stfalcon doesn't mean the classes are same because they have same name.
com.stfalcon.chatkit.messages.MessagesList messagesList = findViewById(R.id.messagesList);
that will be the correct statement. When you use implementation 'com.github.stfalcon:chatkit:0.3.3' and use a library you will get all the classes you can use into your project but you can not modify or convert those classes. If there is a special need to modify the response from one of library class then either use interfaces or create a custom class by extending library class.
Happy Coding !
Related
I have a code similar to the following:
template<class ObjType>
class jsonable
{
private:
static map<string, jsonElem> config;
protected:
virtual void setConfig() = 0;
//other fields and methods in public/private
}
class user : public jsonable<user>
{
protected:
virtual void setConfig();
//other fields and methods in public/private
}
class client : user
{
protected:
virtual void setConfig() {user::setConfig(); /* more config */}
//other fields and methods in public/private
}
The main idea of this code is to save in static variables data related to the class referenced in the template. The problem comes when I want to inherit from the user class: the static variable is shared between user and client classes, instead of one static variable for each class.
I've tried to do something like:
class client : user, jsonable<client>
But a bunch of problems appeared (many methods with same name, and some other related to inherit 2 times the same class). I don't know if there is an elegant way of do this, or even if there is a way at all. (I'm a bit newbie in c++)
Any idea would be welcome! :). And of course, I can "copy" all the contents of user into client but... I would like to do not do that until there are no more options.
Edit:
In order to add context and details to the question, I'm going to explain a bit what I'm doing (or want to do).
Jsonable is a class that provides the ability to serialize into Json another class (helped by https://github.com/nlohmann/json).
To achive this, it uses a static map to store each jsonable-field name and its info (type and position relative to the start of the class in memory, so it can be serialized and deserialized).
The problem comes if a class inherits from another class that inherits from jsonable. Both shares that map, so only the baseclass data is consider when serializing/deserializing. Hope this explanation helps to understand...
Edit2: Giving a full code in a question seems very overkilling to me. If someone wants something to compile, I've uploaded a git repo: https://github.com/HandBe/jsontests
Really thanks to all the people who have put interest on this question!.
A possible solution can be derive client from both user (because it is a user) and jsonable<client> as (private/public apart)
class user : public jsonable<user>
{
protected:
virtual void setConfig();
//other fields and methods in public/private
};
class client: public user, public jsonable<client>
{
virtual void setConfig()
{
user::setConfig();
// more config, referred to jsonable<client>::map
}
}
because it has to implement jsonable for itself (regardless of user).
This is the so-called "stacked parallelogram" inhertiance pattern very common in multiple interface implementations as modular behavior.
Now user and client have each their own configuration
If I understand your problem correctly: you want client to be a user, but also have all the per-class statics defined in jsonable?
Have you considered composition over inheritance? This could work either way:
1) make user a component of client
class client : public jsonable<client>
{
user parent; // could also be a pointer
void setConfig() {parent.setConfig(); /* more config */}
/* ... */
}
2) make jsonable a component:
class user
{
jsonable<user> userjson; // public, private, whatever is appropriate for your design
/* ... */
}
class client : public user
{
jsonable<client> clientjson;
/* ... */
}
First post so be gentle. :) I'm not sure what I am doing wrong here, hopefully someone can help me out.
I have an Class that implements the List interface. This class also has it's own method that will only add an item to the list if it is not already in the list. The trouble is that when I try to use my conditionalAdd method, I get a error stating that it can't find my method because it is looking for it in the WorkflowSubType class. Please see below:
When I instantiate the Class I am using:
List<WorkflowSubType> currentViolations = new Violations();
This is the definition of my class that implements the List interface:
import java.util.*;
public class Violations<E> implements List<E>{
public Violations() {}
public void conditionalAdd(E violation){
if(violation != null)
if(!this.contains(violation))
add(violation);
}
#Override
public <T> T[] toArray(T[] a) {
return null;
}
#Override
public boolean add(E e) {
return false;
}
#Override....
So how come I can't access the conditionalAdd method. The currentViolations object I created is a List, but it's also a Violations type. Am I correct in saying this?
Thanks in advance.
RW
You will need to cast your instance to Violations. If you don't do so, the compiler interprets it as a List, and a List does not have the conditionalAdd method. Do it like this: ((Violations<WorkflowSubType>)currentViolations).conditionalAdd(whatever);
I am trying to write a unit test for a java class that is extending an abstract class? The java class looks sort of like:
public class XYZFilter extends XYZDataFilter{
#Override
protected boolean filterItem(Model d, String sector) {
//method code
return true;
}
}
The junit test class looks like:
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class XYZFilterTest {
Model m = new Model();
String sector = "SECTOR";
#Test
public void testFilterItem() throws Exception {
System.out.println("\nTest filterItem method...");
XYZFilter f = new XYZFilter();
assertTrue(f.filterItem(m, sector));
}
}
So I'm having a problem with the abstract DataFilter which is extended by the Filter class, as well as the Model class. I believe I need to mock these objects using JMockit but I am having a lot of trouble figuring out how to do this. Any advice is appreciated.
The answer is I needed to have the libraries included, JMockit doesn't handle objects in that way.
I am looking for a solution to mock the super call in subclass ButtonClicker.
Class Click {
public void buttonClick() throws java.lang.Exception { /* compiled code */ } }
Class ButtonClicker extends Click {
#Override
public void buttonClick() throws Exception {
super.buttonClick();
} }
Using inheritance reduces testability of your code. Consider replacing inheritance with the delegation and mock the delegate.
Extract the interface IClicker
interface IClicker {
void buttonClick();
}
Implement IClicker in Clicker class. In case that you are working with third-party code consider using Adapter Pattern
Rewrite your ButtonClicker as following:
class ButtonClicker implements IClicker {
Clicker delegate;
ButtonClicker(Clicker delegate) {
this.delegate = delegate;
}
#Override
public void buttonClick() throws Exception {
delegate.buttonClick();
}
}
Now just pass the mock as a constructor parameter:
Clicker mock = Mockito.mock(Clicker.class);
// stubbing here
ButtonClicker buttonClicker = new ButtonClicker(mock);
The answer is no. A mock is only a trivial interface implementation. (I mean interface in the API sense, not the specific Java keyword sense.) So it doesn't know about any implementation details like which class actually implements the functionality (there is no functionality, essentially).
You can create a 'spy' on a real object that will let you mock only some methods and not others, but that also will not let you mock just the super method of a class because the method(s) you choose to mock are typically chosen by the signature, which is the same for both the sub class and the super class.
I'm trying to start using Unit Testing on my current project in Visual Studio 2010. My class structure, however, contains a number of interface and abstract class inheritance relationships.
If two classes are derived from the same abstract class, or interface I'd like to be able to share the testing code between them. I'm not sure how to do this exactly. I'm thinking I create a test class for each interface I want to test, but I'm not sure the correct way to feed my concrete classes into the applicable unit tests.
Update
OK here's an example. Say I have an interface IEmployee , which is implemented by an abstract class Employee, which is then inherited by the two concrete classes Worker and Employee. (Code show below)
Now say I want to create tests that apply to all IEmployees or Employees. Or alternatively create specific tests for specific types of Employees. For example I may want to assert that setting IEmployee.Number to a number less then zero for any implementation of IEmployee throws an exception. I'd prefer to write the tests from the perspective of any IEmployee and then be able to use the tests on any implementation of IEmployee.
Here's another example. I may also want to assert that setting the vacation time for any employee to a value less then zero throws and error. Yet I may also want to have different tests that apply to a specific concrete version of Employee. Say I want to test that Worker throws an exception if they are provided more then 14 days vacation, but a manager can be provided up to 36.
public interface IEmployee
{
string Name {get; set;}
int Number {get; set;}
}
public abstract class Employee:IEmploee
{
string Name {get; set;}
int Number {get;set;}
public abstract int VacationTime(get; set;)
}
public abstract class Worker:IEmployee
{
private int v;
private int vTime;
public abstract int VacationTime
{
get
{
return VTime;
}
set
{
if(value>36) throw new ArgumentException("Exceeded allowed vaction");
if(value<0)throw new ArgumentException("Vacation time must be >0");
vTime= value;
}
}
public void DoSomWork()
{
//Work
}
}
public abstract class Manager:IEmployee
{
public abstract int VacationTime
{
get
{
return VTime;
}
set
{
if(value>14) throw new ArgumentException("Exceeded allowed vaction");
if(value<0)throw new ArgumentException("Vacation time must be >0");
vTime= value;
}
}
public void DoSomeManaging()
{
//manage
}
}
So I guess what I'm looking for is a work flow that will allow me to nest unit tests. So for example when I test the Manager class I want to first test that it passes the Employee and IEmployee tests, and then test specific members such as DoSomeManaging().
I guess I know what you mean. I had the same issue.
My solution was to create a hierarchy also for testing. I'll use the same example you show.
First, have an abstract test class for the base IEmployee.
It has two main things:
i. All the test methods you want.
ii. An abstract method that returns the desired instance of the IEmployee.
[TestClass()]
public abstract class IEmployeeTests
{
protected abstract GetIEmployeeInstance();
[TestMethod()]
public void TestMethod1()
{
IEmployee target = GetIEmployeeInstance();
// do your IEmployee test here
}
}
Second, you have a test class for each implementation of IEmployee, implementing the abstract method and providing appropriate instances of IEmployee.
[TestClass()]
public class WorkerTests : IEmployeeTests
{
protected override GetIEmployeeInstance()
{
return new Worker();
}
}
[TestClass()]
public class ManagerTests : IEmployeeTests
{
protected override GetIEmployeeInstance()
{
return new Manager();
}
}
You can see everything works as expected and VS gives you the expected test methods for each WorkerTests and ManagerTests classes in the TestView window.
You can run them and have the test results for each implementation of the IEmployee interface, having to create the tests only in the base IEmployeeTests class.
You can always add specific test for the derived WorkerTests and ManagerTests classes.
The question would be now, what about classes that implement multiple interfaces, let's say EmployedProgrammer?
public EmployedProgrammer : IEmployee, IProgrammer
{
}
We don't have multiple inheritance in C#, so this is not an option:
[TestClass()]
public EmployedProgrammerIEmployeeTests : IEmployeeTests, IProgrammerTests
{
// this doesn't compile as IEmployeeTests, IProgrammerTests are classes, not interfaces
}
For this scenario, a solution is to have the following test classes:
[TestClass()]
public EmployedProgrammerIEmployeeTests : IEmployeeTests
{
protected override GetIEmployeeInstance()
{
return new EmployedProgrammer();
}
}
[TestClass()]
public EmployedProgrammerIProgrammerTests : IProgrammerTests
{
protected override GetIProgrammerInstance()
{
return new EmployedProgrammer();
}
}
with
[TestClass()]
public abstract class IProgrammerTests
{
protected abstract GetIProgrammerInstance();
[TestMethod()]
public void TestMethod1()
{
IProgrammer target = GetIProgrammerInstance();
// do your IProgrammerTest test here
}
}
I'm using this with good results.
Hope it helps.
Regards,
Jose
What I think you want to do is create unit tests for methods in abstract classes.
I'm not sure it makes sense to want to test a protected method on an abstract class, but if you insist simply extend the class in a class used exclusively for unittesting. That way you can expose the protected methods on the abstract class you want to test through public methods on the extending class that simply call through to the method on the abstract class.
If you have methods in abstract classes that you want unittested, I suggest refactoring them into separate classes and simply expose them as public methods and put those under test. Try looking at your inheritance tree from a 'test-first' perspective and I'm pretty sure you'll come up with that solution (or a similar one) as well.
It seems that you have described "composite unit testing" which is not supported by Visual Studio 2010 unit tests. Such things can be done in MbUnit according to this article. It is possible to create abstract tests in Visual Studio 2010 which is probably not exactly what you want. Here is description how to implement abstract tests in VS (Inheritance Example section).
Use microsoft moles for better testing. so you can mock the abstract base class / static methods etc easily. Please refer the following post for more info
detouring-abstract-base-classes-using-moles
BenzCar benzCar = new BenzCar();
new MCar(benzCar)
{
Drive= () => "Testing"
}.InstanceBehavior = MoleBehaviors.Fallthrough;
var hello = child.Drive();
Assert.AreEqual("Benz Car driving. Testing", hello);
The desire to run the same test against multiple classes usually means you have an opportunity to extract the behavior you want to test into a single class (whether it's the base class or an entirely new class you compose into your existing classes).
Consider your example: instead of implementing vacation limits in Worker and Manager, add a new member variable to Employee, 'MaximumVacationDays', implement the limit in the employee class' setter, and check the limit there:
abstract class Employee {
private int maximumVacationDays;
protected Employee(int maximumVacationDays) {
this.maximumVacationDays = maximumVacationDays
}
public int VacationDays {
set {
if (value > maximumVacationDays)
throw new ArgumentException("Exceeded maximum vacation");
}
}
}
class Worker: Employee {
public Worker(): Employee(14) {}
}
class Manager: Employee {
public Manager(): Employee(36) {}
}
Now you have only one method to test and less code to maintain.