NSubstitue for IDBCommand and error CA2100

388 Views Asked by At

I want substituting IDBCommand with using NSubstitue. I must substitue field CommandText, and I did

string settedCommandText=string.Empty;

IDbCommand fakeCommand = Substitute.For<IDbCommand>();

command.CommandText =Arg.Do<string>(x => settedCommandText = x);

All right, but compiler throw error:

CA2100 The query string passed to 'IDbCommand.CommandText.set(string)' in 'DriverTest.RevertCommandSendRevertInstruction()' could contain the following variables 'Arg.Do(...)'. If any of these variables could come from user input, consider using a stored procedure or a parameterized SQL query instead of building the query with string concatenations.

How can I rewrite this code without suppressing this error. I don't want use System.Diagnostics.CodeAnalysis.SuppressMessage

2

There are 2 best solutions below

0
On

First, it seems like you're creating a fakeCommand and then setting a variable called command.
Second, your Arg.Do<string> needs to be part of what you're passing to a method. You're not setting it as the value of the command.

Have a look here (official documentation) for how it's done.

0
On

I would write

fakeCommand.Received(1).CommandText = Arg.Any<string>();

or

fakeCommand.Received(1).CommandText = "some specific string";

if I wanted to check that the string I expect is added to the command, and

var _ = fakeCommand.Received(1).Commandtext

to check that the value was actually used somewhere. Since this is a fake command, I would think this is about as much as you'd ever want to know.