I have got a requirement to write unit test for main method but i couldn’t do it in normal way
I have tried to do that by using
but its failing or the process is not stopping . Is there any better approach to write unit test for main method
I have got a requirement to write unit test for main method but i couldn’t do it in normal way
I have tried to do that by using
but its failing or the process is not stopping . Is there any better approach to write unit test for main method
2
Answers
The code as written isn’t testable as the method won’t return unless the console receives a signal to terminate the app as part of
Run()
(also having itprivate
over-complicates calling it – you should make itpublic
orinternal
and access it with[InternalsVisibleTo("...")]
). However, if you refactored it to pull out most of the implementation, you could call that method and have theMain()
method call that.You could then ignore the uncovered code of
Main()
(as it’s trivial) with[ExcludeFromCodeCoverage]
This would then give you coverage of most of the method, but how valuable that is other than "chasing code coverage" is a different matter.
When implementing unit tests it is best practise to re=structure your code in ways to facilitate testing. This will include exposing methods that you want to be testable via public interfaces. This in turn will ensure that you only use publicly typed interfaces for the arguments and response types to your methods.