Home > front end >  Testing quotes in Json with xUnit in C# .Net
Testing quotes in Json with xUnit in C# .Net

Time:03-02

I have an assignment where I have to write some code based on some tests. Basically the tests are written and I have to write the code so the test will pass. I know that it may be a stupid question but I tried everything I could think off and searched everywhere (sorry if there is a related post here but I couldn't find it.) So I have multiple tests but with the following two I can't understand. The first one would be:

[Fact]
    // This is the test
    public void IsWrappedInDoubleQuotes()
    {
        Assert.True(IsJsonString(Quoted("abc")));
    }

    //And this is the method I wrote to pass the test
    static bool DoubleQuoted(string input)
    {
        return input.StartsWith("\"") && input.EndsWith("\"");
    }

Everything looked clear until now. One of the following tests is:

[Fact]
    public void HasStartAndEndQuotes()
    {
        Assert.False(IsJsonString("\""));
    }

I can't figure it out why the same function doesn't work on this one. It fails. (I have around 21 test to write code for, just string not including numbers and math operators).

Both of them have start and end quotes and that's why is so confusing. Thank you in advance!!

CodePudding user response:

So I'm assuming you've written the IsJsonString implementation, and DoubleQuoted is one of the criteria you're using in that method to determine whether the input is valid JSON, right?

I'm also assuming Quoted wraps the given input in double-quotes, so abc is converted into "abc", which is a valid string representation.

In the second test, Quoted isn't called on the input, so you're passing in a single character: ". (\" is just a way of telling C# that you actually mean a " and you're not trying to end the string literal in the C# context.) Two of those together would "start and end with quotes" ("") and be a valid JSON string, but a single " isn't a complete string literal. The criteria you've defined in DoubleQuoted recognizes that it technically starts with double-quotes and ends with double-quotes, but it doesn't take into account whether they are the same instance of double-quotes.

  • Related