5

I have a C# application, which includes a service that works with multiple OPC UA Sessions (UnifiedAutomation.UaClient.Session). These sessions are created by connecting to addresses like opc.tcp://localhost:48030 etc.

foreach (ConnectionStringSettings connectionSettings in ConfigurationManager.ConnectionStrings)
{
    var connectionString = connectionSettings.ConnectionString;

    // Ignore non-OPC-connections 
    if (!connectionString.StartsWith("opc.tcp")) continue;

    // Create new session for connection
    var session = new Session
    {
        AutomaticReconnect = true,
        ReconnectDelay = 0
    };

    // Connect to OPC UA Server
    try
    {
        session.Connect(connectionString, SecuritySelection.None);
        Log("OPC UA Session establish.", EventLogEntryType.Information);
    }
    catch (StatusException)
    {
        Log($"No OPC UA Server found at {connectionString}.",
            EventLogEntryType.Warning);
    }
}

I want to unit test the methods of my service but I cannot figure out how to mock the OPC UA sessions.

Any idea if this is possible at all?

jasie
  • 2,192
  • 10
  • 39
  • 54
  • 1
    Are you using those like usual tcp connections or via a client lib? If client lib: which one and do you inject it via DI? Can you post a code example? – Fildor Oct 23 '18 at 07:58
  • Thanks for the feedback, Fildor. They are actual TCP connections. – jasie Oct 23 '18 at 08:07
  • OK. Maybe there is a better way, but personally, I'd create some Factory for `Session` instead of using `new Session` directly, so I could inject another implementation (= Mock). Then it would be testable. Or, since the instance seems always to have the same params, I'd inject a Session instance via DI if you have DI (Dependency Injection) in place anyway. – Fildor Oct 23 '18 at 08:13
  • @jasie did you manage to do this? – JTIM May 20 '21 at 09:37
  • @JTIM Sorry, no, but if I remember correctly, I did not try the proposal of Fildor. Maybe you can give it a go? – jasie May 20 '21 at 09:54
  • I can't test it, but this lib might be useful: https://github.com/OPCFoundation/UA-.NETStandard/tree/master/Tests – jasie Aug 10 '22 at 09:14

0 Answers0