Setting the Notification Type after instantiating

As I want to Unit-Test a Method where a Notification is shown I have to create a Mockobject for the notification and in order to exchange the real notification with the mock I want to inject the notification. When I inject it I have no chance to call anything but the standard constructor of notifaction and following that I can’t give it the ErrorType I want at the time of injection.
There are setters for caption, description and so on but I can’t find a way to tell my injected notifaction that it should be of the Type TYPE_ERROR_MESSAGE.

Is there anything that I can do to set it after instantiation?

In Vaadin 6 this was very easy because you could dfeine the type when you call showNotifaction

main.showNotification("This is a warning",
            "<br/>This is the <i>last</i> warning",
            Window.Notification.TYPE_WARNING_MESSAGE);

As there is only notifaction.show in Vaadin 7 which only takes the page where it should be shown as parameter this is not possible anymore.

I don’t know the code you want to unit-test, but having to mock some UI functionality in order to test one of your methods seems like a code smell for me. Maybe you should better seperate the UI logic from your business logic (have a look at the Model-View-Presenter pattern for this) in order to avoid having to mock UI functionality. Hide any UI logic behind an interface and you can easily mock this UI interface (the principle of MVP).

Guessing from your description, I could imagine that you have the following type of code you want to test:


public void methodToBeTested() {
   // do something
   if (someCondition) {
      Notification.show("Error...");
   }
   // do something more
}

This should be changed to something along the lines of


public interface MyView {
   void showErrorNotification(String message);
}

public class MyClass {

   private MyView view;

   public void methodToBeTested() {
      // do something
      if (someCondition) {
         view.showErrorNotification("Error...");
      }
      // do something more
   }
}

The interface MyView can be mocked without any hassle.

You are absolutely right with that. At the moment I want to use the Notification inside of a presenter class which is not the right the way to do. I will refactor that later but it wouldn’t really solve my problem. For using CDI in the service layer I need my services to be provided in the DI context to make this happen it is the easiest thing to do to wire all components from the root and let the framework handle the injection stuff.
The other thing is that I could write small tests for the view classes too that could verify that notifications are still there, exceptions get thrown and stuff like that.

Anyway I think I could solve the problem by writing a own qualifier and working with a producer here.