3

I have a custom component created in WPF using C#, where I have some validation that are checked when the textbox OnLostFocus is called (it is only when the user leaves the textbox I can do the validation, since only then do I have the complete input string to validate).

How can I trigger the OnLostFocus on the textBox from the unit test?

Thanks

code-zoop
  • 7,312
  • 8
  • 47
  • 56

1 Answers1

3

You're not really clear how you're doing the testing but two things spring to mind.

  • If you actually want the text box to lose focus then set focus to another control by calling someOtherControl.Focus()
  • If you just want to test the OnLostFocus processing then call the method directly.
arx
  • 16,686
  • 2
  • 44
  • 61
  • I do want the unit test to behave as close to the real usage scenario as possible, and this is done by manually creating the component in the test, simulating user input, and then check the validation that happens on OnLostFocus on the manually created component. I have tried as you suggest in your first point, but OnLostFocus is never called on the textbox.First I am creating a canvas. Then the custom component. Then I am adding the custom component as a child of the canvas. Finnaly I am using myCanvas.Focus(), but the OnLostFocus is never called! – code-zoop Sep 22 '10 at 06:45
  • Can a canvas accept focus? Try adding another control to the canvas (e.g. a text box which can definitely accept focus) and set the focus to that. – arx Sep 22 '10 at 11:23
  • Hope you don't mind a reply to such an old post. Calling the OnFocusLost manual from the test solves my problem, but i had to make it public simply for the purpose of the test, i don't consider that good code design. Do you know of conducting the unit test with keeping the function as private? – Cousken Feb 17 '14 at 08:28
  • @Cousken: You can use reflection or a utility class that takes care of the details for you. However, some people consider the testing of private methods to be a bad code smell. It is worth reading the [top few answers to this question](http://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods). – arx Feb 17 '14 at 14:49