Is there a way to skip tests in base classes? - vs-unit-testing-framework

I'm using C# 4.0, Visual Studio 2010 and am annotating my methods/classes with the attributes from the Microsoft.VisualStudio.TestTools.UnitTesting namespace.
I'd like to use inheritance in my test classes where each additional inheritance represents something changing or being created. If I could get it to not run tests from the base classes, then everything would be fine. Here's a rough example:
public class Person
{
public int Energy { get; private set; }
public int AppleCount { get; private set; }
public Person()
{
this.Energy = 10;
this.AppleCount = 5;
}
public void EatApple()
{
this.Energy += 5;
this.AppleCount--;
}
}
[TestClass]
public class PersonTest
{
protected Person _person;
[TestInitialize]
public virtual void Initialize()
{
this._person = new Person();
}
[TestMethod]
public void PersonTestEnergy()
{
Assert.AreEqual(10, this._person.Energy);
}
[TestMethod]
public void PersonTestAppleCount()
{
Assert.AreEqual(5, this._person.AppleCount);
}
}
[TestClass]
public class PersonEatAppleTest : PersonTest
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
this._person.EatApple();
}
[TestMethod]
public void PersonEatAppleTestEnergy()
{
Assert.AreEqual(15, this._person.Energy);
}
[TestMethod]
public void PersonEatAppleTestAppleCount()
{
Assert.AreEqual(4, this._person.AppleCount);
}
}

I asked a coworker and he suggested separating the initializing code from the testing. Inherit all the setup code, but then place all the tests for a particular setup in a class that inherits from said setup code. So the above would become:
public class Person
{
public int Energy { get; private set; }
public int AppleCount { get; private set; }
public Person()
{
this.Energy = 10;
this.AppleCount = 5;
}
public void EatApple()
{
this.Energy += 5;
this.AppleCount--;
}
}
[TestClass]
public class PersonSetup
{
protected Person _person;
[TestInitialize]
public virtual void Initialize()
{
this._person = new Person();
}
}
[TestClass]
public class PersonTest : PersonSetup
{
[TestMethod]
public void PersonTestEnergy()
{
Assert.AreEqual(10, this._person.Energy);
}
[TestMethod]
public void PersonTestAppleCount()
{
Assert.AreEqual(5, this._person.AppleCount);
}
}
[TestClass]
public class PersonEatAppleSetup : PersonSetup
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
this._person.EatApple();
}
}
[TestClass]
public class PersonEatAppleTest : PersonEatAppleSetup
{
[TestMethod]
public void PersonEatAppleTestEnergy()
{
Assert.AreEqual(15, this._person.Energy);
}
[TestMethod]
public void PersonEatAppleTestAppleCount()
{
Assert.AreEqual(4, this._person.AppleCount);
}
}
If someone else knows how to skip inherited methods like I originally asked, then I'll accept that. If not, then eventually I'll accept this answer.

Related

Inheritance in Json Response Spring boot

I have two classes, A and B:
class A{
private int numberOne;
private int numberTwo;
public int getNumberOne() {
return numberOne;
}
public void setNumberOne(int numberOne) {
this.numberOne = numberOne;
}
public int getNumberTwo() {
return numberTwo;
}
public void setNumberTwo(int numberTwo) {
this.numberTwo = numberTwo;
}
}
class B extends A {
private int numberThree;
public int getNumberThree() {
return numberThree;
}
public void setNumberThree(int numberThree) {
this.numberThree = numberThree;
}
}
How do I can like this:
ResponseEntity<A> someMethod(){
return new B(1,2,3);
}
json
{
"numberOne":"1",
"numberTwo":"2"
}
ResponseEntity<B> someMethod(){
return new B(1,2,3);
}
json
{
"numberOne":"1",
"numberTwo":"2",
"numberThree":"3"
}
How can I use JSON ignoring in Spring Boot which I want?
You create new class
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
A.class
public class A {
public A(int numberOne, int numberTwo) {
this.numberOne = numberOne;
this.numberTwo = numberTwo;
}
#JsonView(Views.Public.class)
private int numberOne;
#JsonView(Views.Public.class)
private int numberTwo;
public int getNumberOne() {
return numberOne;
}
public void setNumberOne(int numberOne) {
this.numberOne = numberOne;
}
public int getNumberTwo() {
return numberTwo;
}
public void setNumberTwo(int numberTwo) {
this.numberTwo = numberTwo;
}
}
B.class
public class B extends A{
#JsonView(Views.Internal.class)
private int numberThree;
public B(int numberOne, int numberTwo) {
super(numberOne, numberTwo);
}
public B(int numberOne, int numberTwo, int numberThree) {
super(numberOne, numberTwo);
this.numberThree = numberThree;
}
public int getNumberThree() {
return numberThree;
}
public void setNumberThree(int numberThree) {
this.numberThree = numberThree;
}
}
Controller
#GetMapping("/a-method")
#JsonView(Views.Public.class)
public ResponseEntity<A> getA(){
return ResponseEntity.ok(new B(1,2,3));
}
#GetMapping("/b-method")
#JsonView(Views.Internal.class)
public ResponseEntity<B> getB(){
return ResponseEntity.ok(new B(1,2,3));
}

Castle Windsor Property Injection does not work with dynamic parameters

We want to use NserviceBus Saga's and in order to do that you need parameterless constructors for your saga. The only other way to inject our concerns is to use property injection which does not appear to work. Any help and guidance would be greatly appreciated.
I have posted sample code below that show's the issue.
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For<ClassWithDynamicProperty>()
.DynamicParameters((r, k) =>{ k["testString"] = "test"; }) );
container.Register(
Component.For<TestClassWithPropertyInjection>());
container.Register(
Component.For<TestClassWithConstructorInjection>());
var class1 = container.Resolve<TestClassWithConstructorInjection>();
var class2 = container.Resolve<TestClassWithPropertyInjection>();
Debug.Assert(class1.DynamicClass == null);
Debug.Assert(class2.ClassWithDynamicProperty == null);
}
}
internal class TestClassWithPropertyInjection
{
public TestClassWithPropertyInjection()
{
}
public ClassWithDynamicProperty ClassWithDynamicProperty { get; set; }
}
internal class TestClassWithConstructorInjection
{
private readonly ClassWithDynamicProperty _classWithDynamicProperty;
public TestClassWithConstructorInjection(ClassWithDynamicProperty classWithDynamicProperty)
{
_classWithDynamicProperty = classWithDynamicProperty;
}
public ClassWithDynamicProperty DynamicClass { get { return _classWithDynamicProperty; } }
}
public class ClassWithDynamicProperty
{
public string TestString { get; private set; }
public ClassWithDynamicProperty(string testString)
{
TestString = testString;
}
}

dropwizard: incorrect json resulting from group of items

I am using Dropwizard to deliver a RESTful service. The JSON I EXPECT looks like this:
{"featuredMerchants":
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}}
But the JSON I am GETTING is this:
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}
I have two classes. I have an ApiFeaturedMerchantGroup class that contains a list of ApiFeaturedMerchants.
#JsonRootName("featuredMerchants")
public class ApiFeaturedMerchantGroup {
private List<ApiFeaturedMerchant> apiFeaturedMerchants;
public ApiFeaturedMerchantGroup() {
}
#JsonProperty("featuredMerchant")
public List<ApiFeaturedMerchant> getApiFeaturedMerchants() { return apiFeaturedMerchants; }
public void setApiFeaturedMerchants(List<ApiFeaturedMerchant> apiFeaturedMerchants) { this.apiFeaturedMerchants = apiFeaturedMerchants; }
}
#JsonRootName("featuredMerchant")
public class ApiFeaturedMerchant {
private String browseId;
private int merchantId;
private Integer priority;
private String sourceId;
public ApiFeaturedMerchant() {
}
public String getBrowseId() { return browseId; }
public void setBrowseId(String browseId) { this.browseId = browseId; }
public int getMerchantId() { return merchantId; }
public void setMerchantId(int merchantId) { this.merchantId = merchantId; }
public Integer getPriority() { return priority; }
public void setPriority(Integer priority) { this.priority = priority; }
public String getSourceId() { return sourceId; }
public void setSourceId(String sourceId) { this.sourceId = sourceId; }
}
How do I get the extra level into my JSON, the "featuredMerchants" group that contains the individual "featuredMerchant" items? Do I have the wrong annotations, or am I missing one/some?
It's a setting on ObjectMapperFactory:
ObjectMapperFactory objectMapperFactory = new ObjectMapperFactory();
objectMapperFactory.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper = objectMapperFactory.build();

Castle Windsor Typed Factory Facility

When _fwf.GetFileWatcher is called, always MailWatcher is returning. How can I return FileWatcher class with typed factory facility? I tried code block as below but this gets always the first component.
Also I tried DefaultTypedFactoryComponentSelector but i can't get a result.
public interface IWatcher : IDisposable
{
void StartWatching();
}
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory(x => x.SelectedWith(new FileWatcherSelector())));
_fwf = _container.Resolve<IFileWatcherFactory>();
strong textvar fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For anyone looking at this, using the TypedFactoryFacility, to dictate which type the Factory will create if this varies, you can use the Get[Name] convention, where your interface will have a create method for each implementation type.
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetMailWatcher(string path);
IWatcher GetFileWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().Named("MailWatcher").LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().Named("FileWatcher").LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory());
_fwf = _container.Resolve<IFileWatcherFactory>();
var fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For more information, please refer to :
http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx#Get_methods_lookup_components_by_name_4

Hibernate problem with instruction remove

I have a prbolem with hibernate entitymanager and in particular with the instruction remove.
I try to remove a entity from the db but the system return this error.
ERROR [JDBCExceptionReporter] Cannot delete or update a parent row: a foreign key constraint fails (`datalesson`.`coursematerial_lecture`, CONSTRAINT `FK2471D4A14EC7B08F` FOREIGN KEY (`lectures_id`) REFERENCES `lecture` (`id`))
The line code that generate this errore are this:
private static CleanDatabaseSystemRemote cdsr;
cdsr = (CleanDatabaseSystemRemote) ctx.lookup("CleanDatabaseSystemJNDI");
...
int idCourse = tsr.CreateCourse("Test1", "JUnitTest1", 10, idTrainer);
int idCourseMaterial = tsr.CreateCourseMaterial(idCourse, idTrainer, 1, "CourseMaterial");
int idLecture = tsr.CreateLecture(idCourseMaterial, "Test");
...
cdsr.removeCourseMaterial(idCourseMaterial);
cdsr.removeLecture(idLecture);
cdsr.removeCourse(idCourse);
The CleanDatabaseSystem have:
#Remove
public void removeCourse(int idCourse) {
Course course = new Course();
course = manager.find(Course.class, idCourse);
if(course != null){
manager.remove(course);
}
}
#Remove
public void removeCourseMaterial(int idCourseMaterial) {
CourseMaterial courseMaterial = new CourseMaterial();
courseMaterial = manager.find(CourseMaterial.class, idCourseMaterial);
if(courseMaterial != null){
manager.remove(courseMaterial);
}
}
#Remove
public void removeLecture(int idLecture) {
Lecture lecture = new Lecture();
lecture = manager.find(Lecture.class,idLecture);
if (lecture != null) {
manager.remove(lecture);
}
}
And the entity are
#Entity
public class Course implements java.io.Serializable{
...
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
#ManyToOne(cascade={CascadeType.ALL})
public Trainer getTrainer() {
return trainer;
}
public void setTrainer(Trainer trainer) {
this.trainer = trainer;
}
#ManyToMany(targetEntity = lesson.domain.Trainee.class, cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
#JoinTable(name="COURSE_TRAINEE", joinColumns= #JoinColumn(name="COURSE_ID", unique=false), inverseJoinColumns=#JoinColumn(name="TRAINEE_ID", unique=false))
public Set<Trainee> getStudents() {
return students;
}
public void setStudents(Set<Trainee> students) {
this.students = students;
}
}
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public class CourseMaterial extends LearningObject implements java.io.Serializable{
...
#OneToMany(cascade={CascadeType.ALL})
public Set<Lecture> getLectures() {
return lectures;
}
public void setLectures(Set<Lecture> lectures) {
this.lectures = lectures;
}
public String getMaterialName() {
return materialName;
}
public void setMaterialName(String materialName) {
this.materialName = materialName;
}
public void insertLecture(Lecture lecture){
this.lectures.add(lecture);
}
}
#Entity
public class Lecture implements java.io.Serializable {
...
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
#OneToMany(cascade={CascadeType.ALL})
public Set<Papers> getPapers() {
return papers;
}
public void setPapers(Set<Papers> papers) {
this.papers = papers;
}
#OneToMany(cascade={CascadeType.ALL})
public Set<Slide> getSlides() {
return slides;
}
public void setSlides(Set<Slide> slides) {
this.slides = slides;
}
#OneToMany(cascade={CascadeType.ALL})
public Set<Example> getExamples() {
return examples;
}
public void setExamples(Set<Example> examples) {
this.examples = examples;
}
public void insertPapers(Papers papers){
this.papers.add(papers);
}
public void insertSlide(Slide slide){
this.slides.add(slide);
}
public void insertExample(Example example){
this.examples.add(example);
}
}
I don't understand the problem.
Is the cascade? I have miss any annotations?
Thanks
Looks like your course material is referenced from lectures - you'll probably want to remove the lectures first, and the course material second.