Просмотр исходного кода

Remove some more TestMain references.

Rework how Logger/ErrorManager interact so they can be half
mocked out (or, at least, used in a thread-safe-ish manner).

Change-Id: Ia5899640bdc101793819dab88c3fe6038a759abb
Reviewed-on: http://gerrit.dmdirc.com/2695
Reviewed-by: Greg Holmes <greg@dmdirc.com>
Automatic-Compile: DMDirc Build Manager
tags/0.8rc1
Chris Smith 10 лет назад
Родитель
Сommit
fe114fb56f

+ 8
- 2
src/com/dmdirc/commandparser/CommandLoader.java Просмотреть файл

@@ -68,6 +68,7 @@ import com.dmdirc.commandparser.commands.server.RawServerCommand;
68 68
 import com.dmdirc.commandparser.commands.server.Reconnect;
69 69
 import com.dmdirc.commandparser.commands.server.Umode;
70 70
 import com.dmdirc.config.IdentityManager;
71
+import com.dmdirc.interfaces.ActionController;
71 72
 import com.dmdirc.interfaces.CommandController;
72 73
 import com.dmdirc.plugins.PluginManager;
73 74
 
@@ -90,6 +91,9 @@ public class CommandLoader {
90 91
     /** The identity manager to pass to config-related commands. */
91 92
     private final IdentityManager identityManager;
92 93
 
94
+    /** The action controller to pass to action-aware commands. */
95
+    private final ActionController actionController;
96
+
93 97
     /**
94 98
      * Creates a new instance of {@link CommandLoader}.
95 99
      *
@@ -103,11 +107,13 @@ public class CommandLoader {
103 107
             final LifecycleController lifecycleController,
104 108
             final ServerManager serverManager,
105 109
             final PluginManager pluginManager,
106
-            final IdentityManager identityManager) {
110
+            final IdentityManager identityManager,
111
+            final ActionController actionController) {
107 112
         this.lifecycleController = lifecycleController;
108 113
         this.serverManager = serverManager;
109 114
         this.pluginManager = pluginManager;
110 115
         this.identityManager = identityManager;
116
+        this.actionController = actionController;
111 117
     }
112 118
 
113 119
     /**
@@ -138,7 +144,7 @@ public class CommandLoader {
138 144
         manager.registerCommand(new Ctcp(), Ctcp.INFO);
139 145
         manager.registerCommand(new Disconnect(), Disconnect.INFO);
140 146
         manager.registerCommand(new Ignore(), Ignore.INFO);
141
-        manager.registerCommand(new JoinChannelCommand(), JoinChannelCommand.INFO);
147
+        manager.registerCommand(new JoinChannelCommand(actionController), JoinChannelCommand.INFO);
142 148
         manager.registerCommand(new Message(), Message.INFO);
143 149
         manager.registerCommand(new Nick(), Nick.INFO);
144 150
         manager.registerCommand(new Notice(), Notice.INFO);

+ 13
- 0
src/com/dmdirc/commandparser/commands/channel/Ban.java Просмотреть файл

@@ -32,13 +32,17 @@ import com.dmdirc.commandparser.commands.Command;
32 32
 import com.dmdirc.commandparser.commands.IntelligentCommand;
33 33
 import com.dmdirc.commandparser.commands.context.ChannelCommandContext;
34 34
 import com.dmdirc.commandparser.commands.context.CommandContext;
35
+import com.dmdirc.interfaces.CommandController;
35 36
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
36 37
 import com.dmdirc.ui.input.AdditionalTabTargets;
37 38
 import com.dmdirc.ui.input.TabCompletionType;
38 39
 
40
+import lombok.NoArgsConstructor;
41
+
39 42
 /**
40 43
  * The kick command bans a specified user or host from the channel.
41 44
  */
45
+@NoArgsConstructor
42 46
 public class Ban extends Command implements IntelligentCommand {
43 47
 
44 48
     /** A command info object for this command. */
@@ -46,6 +50,15 @@ public class Ban extends Command implements IntelligentCommand {
46 50
             "ban <user|host> - bans the specified user or host from the channel",
47 51
             CommandType.TYPE_CHANNEL);
48 52
 
53
+    /**
54
+     * Creates a new instance of {@link Ban} using the given command controller.
55
+     *
56
+     * @param controller The controller to use for command information.
57
+     */
58
+    public Ban(final CommandController controller) {
59
+        super(controller);
60
+    }
61
+
49 62
     /** {@inheritDoc} */
50 63
     @Override
51 64
     public void execute(final FrameContainer origin,

+ 13
- 0
src/com/dmdirc/commandparser/commands/channel/KickReason.java Просмотреть файл

@@ -33,14 +33,18 @@ import com.dmdirc.commandparser.commands.CommandOptions;
33 33
 import com.dmdirc.commandparser.commands.IntelligentCommand;
34 34
 import com.dmdirc.commandparser.commands.context.ChannelCommandContext;
35 35
 import com.dmdirc.commandparser.commands.context.CommandContext;
36
+import com.dmdirc.interfaces.CommandController;
36 37
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
37 38
 import com.dmdirc.ui.input.AdditionalTabTargets;
38 39
 import com.dmdirc.ui.input.TabCompletionType;
39 40
 
41
+import lombok.NoArgsConstructor;
42
+
40 43
 /**
41 44
  * The kick command kicks a specified user from the channel.
42 45
  * This version allows the user to specify a reason.
43 46
  */
47
+@NoArgsConstructor
44 48
 @CommandOptions(allowOffline = false)
45 49
 public class KickReason extends Command implements IntelligentCommand {
46 50
 
@@ -49,6 +53,15 @@ public class KickReason extends Command implements IntelligentCommand {
49 53
             "kick <user> [reason] - kicks the specified user from the channel",
50 54
             CommandType.TYPE_CHANNEL);
51 55
 
56
+    /**
57
+     * Creates a new instance of {@link KickReason} using the given command controller.
58
+     *
59
+     * @param controller The controller to use for command information.
60
+     */
61
+    public KickReason(final CommandController controller) {
62
+        super(controller);
63
+    }
64
+
52 65
     /** {@inheritDoc} */
53 66
     @Override
54 67
     public void execute(final FrameContainer origin,

+ 9
- 10
src/com/dmdirc/commandparser/commands/server/JoinChannelCommand.java Просмотреть файл

@@ -24,7 +24,6 @@ package com.dmdirc.commandparser.commands.server;
24 24
 
25 25
 import com.dmdirc.FrameContainer;
26 26
 import com.dmdirc.Server;
27
-import com.dmdirc.actions.ActionManager;
28 27
 import com.dmdirc.actions.CoreActionType;
29 28
 import com.dmdirc.commandparser.BaseCommandInfo;
30 29
 import com.dmdirc.commandparser.CommandArguments;
@@ -34,6 +33,7 @@ import com.dmdirc.commandparser.commands.Command;
34 33
 import com.dmdirc.commandparser.commands.IntelligentCommand;
35 34
 import com.dmdirc.commandparser.commands.context.CommandContext;
36 35
 import com.dmdirc.commandparser.commands.context.ServerCommandContext;
36
+import com.dmdirc.interfaces.ActionController;
37 37
 import com.dmdirc.interfaces.ActionListener;
38 38
 import com.dmdirc.interfaces.actions.ActionType;
39 39
 import com.dmdirc.parser.common.ChannelJoinRequest;
@@ -58,17 +58,17 @@ public class JoinChannelCommand extends Command implements
58 58
             CommandType.TYPE_SERVER);
59 59
 
60 60
     /** A map of channel name mentions. */
61
-    private final MapList<FrameContainer, String> mentions
62
-            = new MapList<FrameContainer, String>();
61
+    private final MapList<FrameContainer, String> mentions = new MapList<>();
63 62
 
64 63
     /**
65 64
      * Creates a new instance of the join channel command.
65
+     *
66
+     * @param controller The action controller to register listeners with.
66 67
      */
67
-    public JoinChannelCommand() {
68
+    public JoinChannelCommand(final ActionController controller) {
68 69
         super();
69 70
 
70
-        ActionManager.getActionManager().registerListener(this,
71
-                CoreActionType.CLIENT_LINE_ADDED);
71
+        controller.registerListener(this, CoreActionType.CLIENT_LINE_ADDED);
72 72
     }
73 73
 
74 74
     /** {@inheritDoc} */
@@ -81,7 +81,7 @@ public class JoinChannelCommand extends Command implements
81 81
             return;
82 82
         }
83 83
 
84
-        final List<ChannelJoinRequest> channels = new ArrayList<ChannelJoinRequest>();
84
+        final List<ChannelJoinRequest> channels = new ArrayList<>();
85 85
 
86 86
         for (String pair : args.getArgumentsAsString().split(",")) {
87 87
             final int index = pair.trim().indexOf(' ');
@@ -107,8 +107,7 @@ public class JoinChannelCommand extends Command implements
107 107
         final String[] parts = source.getStyliser().doLinks(message)
108 108
                 .split(Character.toString(Styliser.CODE_CHANNEL));
109 109
 
110
-        int i = 1;
111
-        for (i = 1; i < parts.length; i += 2) {
110
+        for (int i = 1; i < parts.length; i += 2) {
112 111
             // All of the odd parts of the array are channel names
113 112
             mentions.add(source, parts[i]);
114 113
         }
@@ -166,7 +165,7 @@ public class JoinChannelCommand extends Command implements
166 165
      */
167 166
     protected List<String> checkSource(final FrameContainer source,
168 167
             final boolean checkParents, final boolean checkChildren) {
169
-        final List<String> results = new ArrayList<String>();
168
+        final List<String> results = new ArrayList<>();
170 169
 
171 170
         // Check the window itself
172 171
         if (mentions.containsKey(source)) {

+ 25
- 2
src/com/dmdirc/config/validators/URLProtocolValidator.java Просмотреть файл

@@ -22,6 +22,7 @@
22 22
 
23 23
 package com.dmdirc.config.validators;
24 24
 
25
+import com.dmdirc.config.ConfigManager;
25 26
 import com.dmdirc.config.IdentityManager;
26 27
 import com.dmdirc.util.validators.ValidationResponse;
27 28
 import com.dmdirc.util.validators.Validator;
@@ -31,13 +32,35 @@ import com.dmdirc.util.validators.Validator;
31 32
  */
32 33
 public class URLProtocolValidator implements Validator<String> {
33 34
 
35
+    /** The global configuration to read settings from. */
36
+    private final ConfigManager globalConfig;
37
+
38
+    /**
39
+     * Creates a {@link URLProtocolValidator} that will read from the given
40
+     * config.
41
+     *
42
+     * @param globalConfig The config manager to read protocol info from.
43
+     */
44
+    public URLProtocolValidator(final ConfigManager globalConfig) {
45
+        this.globalConfig = globalConfig;
46
+    }
47
+
48
+    /**
49
+     * Creates a {@link URLProtocolValidator} with the default global config.
50
+     *
51
+     * @deprecated Specify a global config
52
+     */
53
+    @Deprecated
54
+    public URLProtocolValidator() {
55
+        this(IdentityManager.getIdentityManager().getGlobalConfiguration());
56
+    }
57
+
34 58
     /** {@inheritDoc} */
35 59
     @Override
36 60
     public ValidationResponse validate(final String object) {
37 61
         if (object == null || object.isEmpty()) {
38 62
             return new ValidationResponse("Cannot be empty");
39
-        } else if (IdentityManager.getIdentityManager().getGlobalConfiguration()
40
-                .hasOptionString("protocol", object)) {
63
+        } else if (globalConfig.hasOptionString("protocol", object)) {
41 64
             return new ValidationResponse("Cannot already exist");
42 65
         } else {
43 66
             return new ValidationResponse();

+ 30
- 9
src/com/dmdirc/logger/ErrorManager.java Просмотреть файл

@@ -25,6 +25,7 @@ package com.dmdirc.logger;
25 25
 import com.dmdirc.config.ConfigManager;
26 26
 import com.dmdirc.config.IdentityManager;
27 27
 import com.dmdirc.interfaces.ConfigChangeListener;
28
+import com.dmdirc.interfaces.IdentityController;
28 29
 import com.dmdirc.ui.FatalErrorDialog;
29 30
 import com.dmdirc.util.collections.ListenerList;
30 31
 
@@ -39,10 +40,10 @@ import java.util.concurrent.atomic.AtomicLong;
39 40
 /**
40 41
  * Error manager.
41 42
  */
42
-public final class ErrorManager implements ConfigChangeListener {
43
+public class ErrorManager implements ConfigChangeListener {
43 44
 
44 45
     /** Previously instantiated instance of ErrorManager. */
45
-    private static final ErrorManager ME = new ErrorManager();
46
+    private static ErrorManager me;
46 47
 
47 48
     /** A list of exceptions which we don't consider bugs and thus don't report. */
48 49
     private static final Class<?>[] BANNED_EXCEPTIONS = new Class<?>[]{
@@ -59,7 +60,7 @@ public final class ErrorManager implements ConfigChangeListener {
59 60
     private boolean logReports;
60 61
 
61 62
     /** Queue of errors to be reported. */
62
-    private final BlockingQueue<ProgramError> reportQueue = new LinkedBlockingQueue<ProgramError>();
63
+    private final BlockingQueue<ProgramError> reportQueue = new LinkedBlockingQueue<>();
63 64
 
64 65
     /** Thread used for sending errors. */
65 66
     private volatile Thread reportThread;
@@ -74,11 +75,18 @@ public final class ErrorManager implements ConfigChangeListener {
74 75
     private final AtomicLong nextErrorID;
75 76
 
76 77
     /** Creates a new instance of ErrorListDialog. */
77
-    private ErrorManager() {
78
-        errors = new LinkedList<ProgramError>();
78
+    public ErrorManager() {
79
+        errors = new LinkedList<>();
79 80
         nextErrorID = new AtomicLong();
81
+    }
80 82
 
81
-        final ConfigManager config = IdentityManager.getIdentityManager().getGlobalConfiguration();
83
+    /**
84
+     * Initialiases the error manager.
85
+     *
86
+     * @param controller The controller to use to read/write settings.
87
+     */
88
+    public void initialise(final IdentityController controller) {
89
+        final ConfigManager config = controller.getGlobalConfiguration();
82 90
 
83 91
         config.addChangeListener("general", "logerrors", this);
84 92
         config.addChangeListener("general", "submitErrors", this);
@@ -92,8 +100,21 @@ public final class ErrorManager implements ConfigChangeListener {
92 100
      *
93 101
      * @return Instance of ErrorManager
94 102
      */
95
-    public static ErrorManager getErrorManager() {
96
-        return ME;
103
+    public static synchronized ErrorManager getErrorManager() {
104
+        if (me == null) {
105
+            me = new ErrorManager();
106
+            me.initialise(IdentityManager.getIdentityManager());
107
+        }
108
+        return me;
109
+    }
110
+
111
+    /**
112
+     * Sets the singleton instance of the error manager.
113
+     *
114
+     * @param errorManager The error manager to use.
115
+     */
116
+    public static void setErrorManager(final ErrorManager errorManager) {
117
+        me = errorManager;
97 118
     }
98 119
 
99 120
     /**
@@ -348,7 +369,7 @@ public final class ErrorManager implements ConfigChangeListener {
348 369
      */
349 370
     public List<ProgramError> getErrors() {
350 371
         synchronized (errors) {
351
-            return new LinkedList<ProgramError>(errors);
372
+            return new LinkedList<>(errors);
352 373
         }
353 374
     }
354 375
 

+ 18
- 2
src/com/dmdirc/logger/Logger.java Просмотреть файл

@@ -27,6 +27,9 @@ package com.dmdirc.logger;
27 27
  */
28 28
 public final class Logger {
29 29
 
30
+    /** The error manager to report errors to. */
31
+    private static ErrorManager errorManager;
32
+
30 33
     /** Prevent instantiation of a new instance of Logger. */
31 34
     private Logger() {
32 35
         //Ignore
@@ -96,8 +99,21 @@ public final class Logger {
96 99
      *
97 100
      * @return The error manager to be used.
98 101
      */
99
-    private static ErrorManager getErrorManager() {
100
-        return ErrorManager.getErrorManager();
102
+    private static synchronized ErrorManager getErrorManager() {
103
+        if (errorManager == null) {
104
+            errorManager = ErrorManager.getErrorManager();
105
+        }
106
+
107
+        return errorManager;
108
+    }
109
+
110
+    /**
111
+     * Sets the error manager that this logger will use.
112
+     *
113
+     * @param errorManager The error manager to use.
114
+     */
115
+    public static void setErrorManager(final ErrorManager errorManager) {
116
+        Logger.errorManager = errorManager;
101 117
     }
102 118
 
103 119
 }

+ 20
- 8
test/com/dmdirc/actions/wrappers/AliasWrapperTest.java Просмотреть файл

@@ -22,7 +22,7 @@
22 22
 
23 23
 package com.dmdirc.actions.wrappers;
24 24
 
25
-import com.dmdirc.TestMain;
25
+import com.dmdirc.ServerManager;
26 26
 import com.dmdirc.actions.Action;
27 27
 import com.dmdirc.actions.ActionCondition;
28 28
 import com.dmdirc.actions.CoreActionComparison;
@@ -30,33 +30,45 @@ import com.dmdirc.actions.CoreActionComponent;
30 30
 import com.dmdirc.actions.CoreActionType;
31 31
 import com.dmdirc.interfaces.CommandController;
32 32
 import com.dmdirc.interfaces.actions.ActionType;
33
+import com.dmdirc.logger.ErrorManager;
34
+import com.dmdirc.logger.Logger;
33 35
 
34 36
 import java.util.ArrayList;
35 37
 import java.util.List;
36 38
 
37 39
 import org.junit.Before;
40
+import org.junit.BeforeClass;
38 41
 import org.junit.Test;
42
+import org.junit.runner.RunWith;
43
+import org.mockito.Mock;
44
+import org.mockito.runners.MockitoJUnitRunner;
39 45
 
40 46
 import static org.junit.Assert.*;
41 47
 import static org.mockito.Mockito.*;
42 48
 
49
+@RunWith(MockitoJUnitRunner.class)
43 50
 public class AliasWrapperTest {
44 51
 
45
-    private Action action;
46
-    private ActionCondition condition;
52
+    @Mock private Action action;
53
+    @Mock private ActionCondition condition;
54
+    @Mock private ServerManager serverManager;
55
+    @Mock private CommandController commandController;
47 56
     private List<ActionCondition> conditions;
48 57
 
49 58
     private AliasWrapper aliasWrapper;
50 59
 
60
+    @BeforeClass
61
+    public static void overrideLogger() {
62
+        // We expect errors to be generated, so mock out the error manager.
63
+        Logger.setErrorManager(mock(ErrorManager.class));
64
+    }
65
+
51 66
     @Before
52 67
     public void setup() {
53
-        final CommandController controller = mock(CommandController.class);
54
-        when(controller.getCommandChar()).thenReturn('!');
68
+        when(commandController.getCommandChar()).thenReturn('!');
55 69
 
56
-        action = mock(Action.class);
57
-        condition = mock(ActionCondition.class);
58 70
         conditions = new ArrayList<>();
59
-        aliasWrapper = new AliasWrapper(controller, TestMain.getTestMain().getServerManager());
71
+        aliasWrapper = new AliasWrapper(commandController, serverManager);
60 72
 
61 73
         when(condition.getArg()).thenReturn(1);
62 74
         when(condition.getComparison()).thenReturn(CoreActionComparison.STRING_EQUALS);

+ 7
- 5
test/com/dmdirc/commandparser/commands/HelpTest.java Просмотреть файл

@@ -23,13 +23,13 @@ package com.dmdirc.commandparser.commands;
23 23
 
24 24
 import com.dmdirc.interfaces.LifecycleController;
25 25
 import com.dmdirc.ServerManager;
26
-import com.dmdirc.TestMain;
27 26
 import com.dmdirc.commandparser.CommandInfo;
28 27
 import com.dmdirc.commandparser.CommandLoader;
29 28
 import com.dmdirc.commandparser.CommandManager;
30 29
 import com.dmdirc.commandparser.CommandType;
31 30
 import com.dmdirc.config.IdentityManager;
32 31
 import com.dmdirc.config.InvalidIdentityFileException;
32
+import com.dmdirc.interfaces.ActionController;
33 33
 import com.dmdirc.plugins.PluginManager;
34 34
 
35 35
 import java.util.LinkedList;
@@ -61,15 +61,17 @@ public class HelpTest {
61 61
     public static List<Object[]> data() throws InvalidIdentityFileException {
62 62
         final List<Object[]> res = new LinkedList<>();
63 63
 
64
-        TestMain.getTestMain();
64
+        final ServerManager serverManager = mock(ServerManager.class);
65
+        final CommandManager commandManager = new CommandManager(serverManager);
65 66
         new CommandLoader(
66 67
                 mock(LifecycleController.class),
67
-                mock(ServerManager.class),
68
+                serverManager,
68 69
                 mock(PluginManager.class),
69
-                mock(IdentityManager.class)).loadCommands(CommandManager.getCommandManager());
70
+                mock(IdentityManager.class),
71
+                mock(ActionController.class)).loadCommands(commandManager);
70 72
 
71 73
         for (CommandType type : CommandType.values()) {
72
-            for (CommandInfo command : CommandManager.getCommandManager().getCommands(type).keySet()) {
74
+            for (CommandInfo command : commandManager.getCommands(type).keySet()) {
73 75
                 res.add(new Object[]{command});
74 76
             }
75 77
         }

+ 17
- 10
test/com/dmdirc/commandparser/commands/channel/BanTest.java Просмотреть файл

@@ -24,32 +24,39 @@ package com.dmdirc.commandparser.commands.channel;
24 24
 
25 25
 import com.dmdirc.Channel;
26 26
 import com.dmdirc.FrameContainer;
27
-import com.dmdirc.TestMain;
28 27
 import com.dmdirc.commandparser.CommandArguments;
29 28
 import com.dmdirc.commandparser.commands.context.ChannelCommandContext;
29
+import com.dmdirc.interfaces.CommandController;
30 30
 import com.dmdirc.parser.interfaces.ChannelClientInfo;
31 31
 import com.dmdirc.parser.interfaces.ChannelInfo;
32 32
 import com.dmdirc.parser.interfaces.ClientInfo;
33 33
 
34
-import org.junit.BeforeClass;
34
+import org.junit.Before;
35 35
 import org.junit.Test;
36
+import org.junit.runner.RunWith;
37
+import org.mockito.Mock;
38
+import org.mockito.runners.MockitoJUnitRunner;
36 39
 
37 40
 import static org.mockito.Mockito.*;
38 41
 
42
+@RunWith(MockitoJUnitRunner.class)
39 43
 public class BanTest {
40 44
 
41
-    @BeforeClass
42
-    public static void setUpClass() throws Exception {
43
-        TestMain.getTestMain();
44
-    }
45
+    @Mock private CommandController controller;
46
+    private Ban command;
45 47
 
46
-    private final Ban command = new Ban();
48
+    @Before
49
+    public void setup() {
50
+        when(controller.getCommandChar()).thenReturn('/');
51
+        when(controller.getSilenceChar()).thenReturn('.');
52
+        command = new Ban(controller);
53
+    }
47 54
 
48 55
     @Test
49 56
     public void testUsage() {
50 57
         final FrameContainer tiw = mock(FrameContainer.class);
51 58
         final Channel channel = mock(Channel.class);
52
-        command.execute(tiw, new CommandArguments("/ban"),
59
+        command.execute(tiw, new CommandArguments(controller, "/ban"),
53 60
                 new ChannelCommandContext(null, Ban.INFO, channel));
54 61
 
55 62
         verify(tiw).addLine(eq("commandUsage"), anyChar(), anyString(), anyString());
@@ -69,7 +76,7 @@ public class BanTest {
69 76
         when(ccInfo.getClient()).thenReturn(clientInfo);
70 77
         when(clientInfo.getHostname()).thenReturn("my.host.name");
71 78
 
72
-        command.execute(container, new CommandArguments("/ban user"),
79
+        command.execute(container, new CommandArguments(controller, "/ban user"),
73 80
                 new ChannelCommandContext(null, Ban.INFO, channel));
74 81
 
75 82
         verify(channelInfo).alterMode(true, 'b', "*!*@my.host.name");
@@ -85,7 +92,7 @@ public class BanTest {
85 92
 
86 93
         when(channel.getChannelInfo()).thenReturn(channelInfo);
87 94
 
88
-        command.execute(container, new CommandArguments("/ban *!*@my.host.name"),
95
+        command.execute(container, new CommandArguments(controller, "/ban *!*@my.host.name"),
89 96
                 new ChannelCommandContext(null, Ban.INFO, channel));
90 97
 
91 98
         verify(channelInfo).alterMode(true, 'b', "*!*@my.host.name");

+ 18
- 11
test/com/dmdirc/commandparser/commands/channel/KickReasonTest.java Просмотреть файл

@@ -22,34 +22,41 @@
22 22
 
23 23
 package com.dmdirc.commandparser.commands.channel;
24 24
 
25
-import com.dmdirc.TestMain;
26 25
 import com.dmdirc.Channel;
27 26
 import com.dmdirc.FrameContainer;
28 27
 import com.dmdirc.commandparser.CommandArguments;
29 28
 import com.dmdirc.commandparser.commands.context.ChannelCommandContext;
30 29
 import com.dmdirc.config.ConfigManager;
30
+import com.dmdirc.interfaces.CommandController;
31 31
 import com.dmdirc.parser.irc.IRCChannelClientInfo;
32 32
 import com.dmdirc.parser.irc.IRCChannelInfo;
33 33
 
34
-import org.junit.BeforeClass;
34
+import org.junit.Before;
35 35
 import org.junit.Test;
36
+import org.junit.runner.RunWith;
37
+import org.mockito.Mock;
38
+import org.mockito.runners.MockitoJUnitRunner;
36 39
 
37 40
 import static org.mockito.Mockito.*;
38 41
 
42
+@RunWith(MockitoJUnitRunner.class)
39 43
 public class KickReasonTest {
40 44
 
41
-    @BeforeClass
42
-    public static void setUpClass() throws Exception {
43
-        TestMain.getTestMain();
44
-    }
45
+    private KickReason command;
46
+    @Mock private CommandController controller;
45 47
 
46
-    private final KickReason command = new KickReason();
48
+    @Before
49
+    public void setup() {
50
+        when(controller.getCommandChar()).thenReturn('/');
51
+        when(controller.getSilenceChar()).thenReturn('.');
52
+        command = new KickReason(controller);
53
+    }
47 54
 
48 55
     @Test
49 56
     public void testUsage() {
50 57
         final FrameContainer tiw = mock(FrameContainer.class);
51 58
         final Channel channel = mock(Channel.class);
52
-        command.execute(tiw, new CommandArguments("/kick"),
59
+        command.execute(tiw, new CommandArguments(controller, "/kick"),
53 60
                 new ChannelCommandContext(null, KickReason.INFO, channel));
54 61
 
55 62
         verify(tiw).addLine(eq("commandUsage"), anyChar(), anyString(), anyString());
@@ -64,7 +71,7 @@ public class KickReasonTest {
64 71
         when(channel.getChannelInfo()).thenReturn(channelInfo);
65 72
         when(channelInfo.getChannelClient(anyString())).thenReturn(null);
66 73
 
67
-        command.execute(tiw, new CommandArguments("/kick user1"),
74
+        command.execute(tiw, new CommandArguments(controller, "/kick user1"),
68 75
                 new ChannelCommandContext(null, KickReason.INFO, channel));
69 76
 
70 77
         verify(tiw).addLine(eq("commandError"), matches(".*user1"));
@@ -80,7 +87,7 @@ public class KickReasonTest {
80 87
         when(channel.getChannelInfo()).thenReturn(channelInfo);
81 88
         when(channelInfo.getChannelClient("user1")).thenReturn(cci);
82 89
 
83
-        command.execute(tiw, new CommandArguments("/kick user1 reason here"),
90
+        command.execute(tiw, new CommandArguments(controller, "/kick user1 reason here"),
84 91
                 new ChannelCommandContext(null, KickReason.INFO, channel));
85 92
 
86 93
         verify(cci).kick("reason here");
@@ -99,7 +106,7 @@ public class KickReasonTest {
99 106
         when(channelInfo.getChannelClient("user1")).thenReturn(cci);
100 107
         when(manager.getOption("general", "kickmessage")).thenReturn("reason here");
101 108
 
102
-        command.execute(tiw, new CommandArguments("/kick user1"),
109
+        command.execute(tiw, new CommandArguments(controller, "/kick user1"),
103 110
                 new ChannelCommandContext(null, KickReason.INFO, channel));
104 111
 
105 112
         verify(cci).kick("reason here");

+ 6
- 10
test/com/dmdirc/commandparser/commands/flags/CommandFlagHandlerTest.java Просмотреть файл

@@ -21,16 +21,14 @@
21 21
  */
22 22
 package com.dmdirc.commandparser.commands.flags;
23 23
 
24
-import com.dmdirc.TestMain;
25 24
 import com.dmdirc.FrameContainer;
26 25
 import com.dmdirc.commandparser.CommandArguments;
27
-import com.dmdirc.config.InvalidIdentityFileException;
26
+import com.dmdirc.interfaces.CommandController;
28 27
 
29 28
 import java.util.Arrays;
30 29
 import java.util.List;
31 30
 import java.util.Map;
32 31
 
33
-import org.junit.BeforeClass;
34 32
 import org.junit.Test;
35 33
 import org.junit.runner.RunWith;
36 34
 import org.junit.runners.Parameterized;
@@ -55,11 +53,6 @@ public class CommandFlagHandlerTest {
55 53
     private final CommandFlag[] flags;
56 54
     private final int[] offsets;
57 55
 
58
-    @BeforeClass
59
-    public static void setupClass() throws InvalidIdentityFileException {
60
-        TestMain.getTestMain();
61
-    }
62
-
63 56
     public CommandFlagHandlerTest(String input, CommandFlag[] flags, int[] offsets) {
64 57
         noArgsFlag3.addEnabled(noArgsFlag4);
65 58
         noArgsFlag3.addDisabled(noArgsFlag1);
@@ -75,9 +68,12 @@ public class CommandFlagHandlerTest {
75 68
     @Test
76 69
     public void testParse() {
77 70
         final FrameContainer container = mock(FrameContainer.class);
71
+        final CommandController controller = mock(CommandController.class);
72
+        when(controller.getCommandChar()).thenReturn('/');
73
+        when(controller.getSilenceChar()).thenReturn('.');
78 74
 
79
-        final Map<CommandFlag, Integer> results
80
-                = handler.parse(container, new CommandArguments(input));
75
+        final Map<CommandFlag, Integer> results = handler.parse(container,
76
+                new CommandArguments(controller, input));
81 77
 
82 78
         if (flags == null) {
83 79
             assertNull("Command should fail: " + input, results);

+ 10
- 9
test/com/dmdirc/config/validators/URLProtocolValidatorTest.java Просмотреть файл

@@ -22,30 +22,31 @@
22 22
 
23 23
 package com.dmdirc.config.validators;
24 24
 
25
-import com.dmdirc.TestMain;
26
-import com.dmdirc.config.IdentityManager;
25
+import com.dmdirc.config.ConfigManager;
27 26
 import com.dmdirc.config.InvalidIdentityFileException;
28 27
 
29 28
 import org.junit.Test;
29
+import org.junit.runner.RunWith;
30
+import org.mockito.Mock;
31
+import org.mockito.runners.MockitoJUnitRunner;
30 32
 
33
+import static org.mockito.Mockito.*;
31 34
 import static org.junit.Assert.*;
32 35
 
36
+@RunWith(MockitoJUnitRunner.class)
33 37
 public class URLProtocolValidatorTest {
34 38
 
39
+    @Mock private ConfigManager configManager;
40
+
35 41
     @Test
36 42
     public void testValidate() throws InvalidIdentityFileException {
37
-        TestMain.getTestMain();
38
-        IdentityManager.getIdentityManager().getGlobalConfigIdentity()
39
-                .setOption("protocol", "unit-test-1", "BROWSER");
43
+        when(configManager.hasOptionString("protocol", "unit-test-1")).thenReturn(true);
40 44
 
41
-        final URLProtocolValidator validator = new URLProtocolValidator();
45
+        final URLProtocolValidator validator = new URLProtocolValidator(configManager);
42 46
         assertTrue(validator.validate(null).isFailure());
43 47
         assertTrue(validator.validate("").isFailure());
44 48
         assertTrue(validator.validate("unit-test-1").isFailure());
45 49
         assertFalse(validator.validate("unit-test-2").isFailure());
46
-
47
-        IdentityManager.getIdentityManager().getGlobalConfigIdentity()
48
-                .unsetOption("protocol", "unit-test-1");
49 50
     }
50 51
 
51 52
 }

+ 22
- 13
test/com/dmdirc/logger/DMDircExceptionHandlerTest.java Просмотреть файл

@@ -22,29 +22,38 @@
22 22
 package com.dmdirc.logger;
23 23
 
24 24
 
25
-import com.dmdirc.TestMain;
26
-
27
-import org.junit.BeforeClass;
25
+import org.junit.Before;
28 26
 import org.junit.Test;
27
+import org.junit.runner.RunWith;
28
+import org.mockito.Mock;
29
+import org.mockito.runners.MockitoJUnitRunner;
29 30
 
30
-import static org.junit.Assert.*;
31
+import static org.mockito.Mockito.*;
31 32
 
33
+@RunWith(MockitoJUnitRunner.class)
32 34
 public class DMDircExceptionHandlerTest {
33 35
 
34
-    @BeforeClass
35
-    public static void setUpClass() throws Exception {
36
-        TestMain.getTestMain();
36
+    @Mock private ErrorManager errorManager;
37
+    private DMDircExceptionHandler eh;
38
+
39
+    @Before
40
+    public void setup() {
41
+        Logger.setErrorManager(errorManager);
42
+        eh = new DMDircExceptionHandler();
37 43
     }
38 44
 
39 45
     @Test
40 46
     public void testUncaughtException() {
41
-        final DMDircExceptionHandler eh = new DMDircExceptionHandler();
42
-
43
-        final int initial = ErrorManager.getErrorManager().getErrorCount();
44
-
45
-        eh.uncaughtException(null, new Exception());
47
+        final Exception exception = new Exception();
48
+        eh.uncaughtException(null, exception);
49
+        verify(errorManager).addError(eq(ErrorLevel.HIGH), anyString(), same(exception), eq(true));
50
+    }
46 51
 
47
-        assertEquals(initial + 1, ErrorManager.getErrorManager().getErrorCount());
52
+    @Test
53
+    public void testUncaughtError() {
54
+        final Error error = new Error();
55
+        eh.uncaughtException(null, error);
56
+        verify(errorManager).addError(eq(ErrorLevel.FATAL), anyString(), same(error), eq(true));
48 57
     }
49 58
 
50 59
 }

+ 23
- 75
test/com/dmdirc/logger/ProgramErrorTest.java Просмотреть файл

@@ -21,113 +21,61 @@
21 21
  */
22 22
 package com.dmdirc.logger;
23 23
 
24
-import com.dmdirc.TestMain;
25
-import com.dmdirc.config.InvalidIdentityFileException;
26 24
 
27 25
 import java.util.Arrays;
28 26
 import java.util.Date;
29 27
 
30
-import org.junit.BeforeClass;
28
+import org.junit.Before;
31 29
 import org.junit.Test;
30
+import org.junit.runner.RunWith;
31
+import org.mockito.Mock;
32
+import org.mockito.runners.MockitoJUnitRunner;
32 33
 
33 34
 import static org.junit.Assert.*;
34 35
 
36
+@RunWith(MockitoJUnitRunner.class)
35 37
 public class ProgramErrorTest {
36 38
 
37
-    @BeforeClass
38
-    public static void setup() throws InvalidIdentityFileException {
39
-        TestMain.getTestMain();
39
+    @Mock private ErrorManager errorManager;
40
+
41
+    @Before
42
+    public void setup() {
43
+        ErrorManager.setErrorManager(errorManager);
40 44
     }
41 45
 
42
-    @Test
46
+    @Test(expected = IllegalArgumentException.class)
43 47
     public void testConstructorNegativeID() {
44
-        boolean exception = false;
45
-
46
-        try {
47
-            new ProgramError(-1, ErrorLevel.HIGH, "moo", new String[0], new Date());
48
-        } catch (Exception ex) {
49
-            exception = true;
50
-        }
51
-
52
-        assertTrue(exception);
48
+        new ProgramError(-1, ErrorLevel.HIGH, "moo", new String[0], new Date());
53 49
     }
54 50
 
55
-    @Test
51
+    @Test(expected = IllegalArgumentException.class)
56 52
     public void testConstructorNullErrorLevel() {
57
-        boolean exception = false;
58
-
59
-        try {
60
-            new ProgramError(1, null, "moo", new String[0], new Date());
61
-        } catch (Exception ex) {
62
-            exception = true;
63
-        }
64
-
65
-        assertTrue(exception);
53
+        new ProgramError(1, null, "moo", new String[0], new Date());
66 54
     }
67 55
 
68
-    @Test
56
+    @Test(expected = IllegalArgumentException.class)
69 57
     public void testConstructorNullMessage() {
70
-        boolean exception = false;
71
-
72
-        try {
73
-            new ProgramError(1, ErrorLevel.HIGH, null, new String[0], new Date());
74
-        } catch (Exception ex) {
75
-            exception = true;
76
-        }
77
-
78
-        assertTrue(exception);
58
+        new ProgramError(1, ErrorLevel.HIGH, null, new String[0], new Date());
79 59
     }
80 60
 
81
-    @Test
61
+    @Test(expected = IllegalArgumentException.class)
82 62
     public void testConstructorEmptyMessage() {
83
-        boolean exception = false;
84
-
85
-        try {
86
-            new ProgramError(1, ErrorLevel.HIGH, "", new String[0], new Date());
87
-        } catch (Exception ex) {
88
-            exception = true;
89
-        }
90
-
91
-        assertTrue(exception);
63
+        new ProgramError(1, ErrorLevel.HIGH, "", new String[0], new Date());
92 64
     }
93 65
 
94
-    @Test
66
+    @Test(expected = IllegalArgumentException.class)
95 67
     public void testConstructorNullTrace() {
96
-        boolean exception = false;
97
-
98
-        try {
99
-            new ProgramError(1, ErrorLevel.HIGH, "moo", null, new Date());
100
-        } catch (Exception ex) {
101
-            exception = true;
102
-        }
103
-
104
-        assertTrue(exception);
68
+        new ProgramError(1, ErrorLevel.HIGH, "moo", null, new Date());
105 69
     }
106 70
 
107
-    @Test
71
+    @Test(expected = IllegalArgumentException.class)
108 72
     public void testConstructorNullDate() {
109
-        boolean exception = false;
110
-
111
-        try {
112
-            new ProgramError(1, ErrorLevel.HIGH, "moo", new String[0], null);
113
-        } catch (Exception ex) {
114
-            exception = true;
115
-        }
116
-
117
-        assertTrue(exception);
73
+        new ProgramError(1, ErrorLevel.HIGH, "moo", new String[0], null);
118 74
     }
119 75
 
120 76
     @Test
121 77
     public void testConstructorGood() {
122
-        boolean exception = false;
123
-
124
-        try {
125
-            new ProgramError(1, ErrorLevel.HIGH, "moo", new String[0], new Date());
126
-        } catch (IllegalArgumentException ex) {
127
-            exception = true;
128
-        }
129
-
130
-        assertFalse(exception);
78
+        new ProgramError(1, ErrorLevel.HIGH, "moo", new String[0], new Date());
131 79
     }
132 80
 
133 81
     @Test

Загрузка…
Отмена
Сохранить