package ru.rsdn.patterns.behavioral.observer.test;

import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.Assert;
import org.junit.Test;

import ru.rsdn.patterns.behavioral.observer.ISubscriber;

/**
 * Тестирование примера издателя, использующего слабую связь с подписчиками
 */
public class ConcretePublisherTest {
	/**
	 * Тестирование оповещения
	 */
	@Test
	public void testNotify() {
		final ConcretePublisher publisher = new ConcretePublisher();
		final boolean state = true;
		final AtomicBoolean notified = new AtomicBoolean();
		publisher.subscribe(new ISubscriber() {
			public void eventHappen() {
				notified.set(true);
				Assert.assertTrue(publisher.getState() == state);
			}
		});
		publisher.setState(state);
		Assert.assertTrue(notified.get());
	}

	/**
	 * Тестирование слабой связи
	 */
	@Test
	public void testWeakReference() {
		final ConcretePublisher publisher = new ConcretePublisher();
		ISubscriber subscriber = new ISubscriber() {
			public void eventHappen() {
				Assert.fail();
			}
		};
		publisher.subscribe(subscriber);
		subscriber = null;
		System.gc();
		Assert.assertFalse(publisher.getSubscribersCount() > 0);
	}
}
