Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

ADD two test cases for the method notifyObservers() package com.hundredwordsgof.

ID: 3716848 • Letter: A

Question

ADD two test cases for the method notifyObservers()

package com.hundredwordsgof.flyweightobserver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* Subject knows its observers. Any number of Observer objects may observe a
* subject.
*
*/
abstract class Subject {

private List observers = new ArrayList();

public void attach(Observer observer) {
observers.add(observer);
}

public void dettach(Observer observer) {
observers.remove(observer);
}

public void notifyObservers() {
for (Iterator iterator = observers.iterator(); iterator.hasNext();) {
Observer observer = (Observer) iterator.next();
observer.update();
}
}

}

into this file observertest.java

package com.hundredwordsgof.flyweightobserver;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* Test Observer pattern.
*/
public class ObserverTest {

@Test
public void testObserver() throws CloneNotSupportedException {

FlyweightSubjectFactory fwSFactory = new FlyweightSubjectFactory();

FlyweightSubject subject = (FlyweightSubject) fwSFactory.getSubject("ObserverTest", "testSubject");

UnSharedFlyweightObserver observer = new UnSharedFlyweightObserver(subject);
subject.attach(observer);
subject.setState(1);

// changes via subject.setState is propagated towards observer
assertEquals(1, ((FlyweightObserver) observer).getWhatObserverKnows());

subject.dettach(observer);
subject.setState(0);

// observer is detached so changes are not propageted
assertEquals(1, ((FlyweightObserver) observer).getWhatObserverKnows());
}
}

Explanation / Answer

ANSWER:

Below are the test cases for the method notifyObservers when it is executed.

1. To know whether the observer knows the subject that he is observing.

2. To verify whether the subject he/she is observing is applicable to a specific state.

3. Need to have a null check the Observer when it is getting added

So we need to call the specific methods to verify this scenario to not to gets failed while the notifyObserver method is being called.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote