This is a migrated thread and some comments may be shown as answers.

How to throw a exception after checking string.IsnullorEmpty

1 Answer 121 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Surya
Top achievements
Rank 1
Surya asked on 06 Feb 2020, 01:52 PM

Hi ,

 

I am actually intended to write a UT  for the following code.

Private void GetVersion(){

string version=GetLatest();

if(string.IsNullOrEmpty(version))

Throw new InvalidException("Ivalid version");

 

How to write a unit test for the above code?

1 Answer, 1 is accepted

Sort by
0
Mihail
Telerik team
answered on 07 Feb 2020, 10:24 AM

Hi Surya,

From your post, it is not clear what you are trying to achieve with those unit tests. This is why I will assume you would like to test whether the exception will be thrown or not in case the version string is an empty string or not. Here are the two unit tests for this scenario.

 

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void TestMethod()
        {
            var foo = new Foo();

            Mock.NonPublic.Arrange<string>(foo, "GetLatest").Returns(string.Empty);

            var privateAccessor = Mock.NonPublic.MakePrivateAccessor(foo);
            privateAccessor.RethrowOriginalOnCallMethod = true;
            privateAccessor.CallMethod("GetVersion");
        }

        [TestMethod]
        public void TestMethod2()
        {
            var foo = new Foo();

            Mock.NonPublic.Arrange<string>(foo, "GetLatest").Returns("latest version");

            var privateAccessor = Mock.NonPublic.MakePrivateAccessor(foo);
            privateAccessor.CallMethod("GetVersion");
        }

In case this is not what you are trying to achieve please provide detailed information on your scenario.

Regards,
Mihail
Progress Telerik

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
General Discussions
Asked by
Surya
Top achievements
Rank 1
Answers by
Mihail
Telerik team
Share this question
or