0

I am pretty new to coding and unit tests. I am writing a unit test for a method converts string to date.

What do I assert for a positive test

it goes like below

String s1 = "11/11/2018"; Date returnedValue = Class.ConvertToDate(s1); assert(????);

Surs
  • 1
  • 1
  • 1
    Possible duplicate of [New to unit testing, how to write great tests?](https://stackoverflow.com/questions/3258733/new-to-unit-testing-how-to-write-great-tests) – Alessandro Da Rugna Nov 23 '18 at 23:29
  • All tests should be based on expected result. Create expected data first, then assert that returned value is same as expected. – Fabio Nov 23 '18 at 23:49

1 Answers1

0

I am not sure what methods the Date class in your code snippet provides, so I will assume that it has the following methods: getDayNrInMonth which returns the day as an int value starting from 1, getMonthNrInYear which returns the month as an int starting from 1, and getYearNr which returns the year as an int value (lets just ignore that there are different calendarian systems, and that is all for the Gregorian calendar).

The important question you would have to answer first is, what the goal of the test would be. There are several possible goals that you could test for - which means that you probably should end up with writing several tests. Let's assume you want to test that the year part was converted correctly. Then, the assertion could look like follows:

assert(returnedValue.getYearNr() == 2018);

Most likely, however, your test framework will provide something better for you here, possibly a function assertEquals, which you could then use as follows:

assertEquals(returnedValue.getYearNr(), 2018);

If in contrast you want to check that the month is converted correctly, you will immediately realize that the test example you have chosen is not ideal:

assertEquals(returnedValue.getMonthNrInYear(), 11);

As in your example day and month both are 11, this test would not be very reliable. So to test the correct conversion of the day and the month, the input strings should be chosen to have distinguishable values for the two.

While you move on with learning to program and to test, you will find that there are many more aspects that could be considered. The links in the comments can help you. However, hopefully the above points support you in taking the next steps.

Dirk Herrmann
  • 5,550
  • 1
  • 21
  • 47