简体   繁体   中英

Testing Mocked object constructor

I'm trying to test an object "SqlGymSessionRepository" that takes an int on initialization. If no parameter is supplied I want it to throw an error. I can't figure out how this should work. I have something like this:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Throw_Exception_If_Not_Session_Id()
{
    var mockRepos = new Mock<SqlGymSessionRepository>();
}

I'm unsure of where the constructor should be tested?

You don't want to mock the class (implementation) you're testing. You want to mock dependencies on a class. If you're testing SqlGymSessionRepository then you don't want a mock of it, you want its implementation. The mocking is for any other classes on which SqlGymSessionRepository depends, which you would then supply to it for your tests.

Call the constructor directly.

If you want to test the constructor, call it:

new SqlGymSessionRepository(null);

Update per the comments:

You are stating that it takes a nullable int. Then the compiler will ensure that it will always get called with either null or an integer value. If null is an invalid initialization valid, your code should throw an exception and you can test that. You don't need to test that the method gets called without a parameter. C# is statically typed, so code won't compile unless a value is provided for all required parameters.

new SqlGymSessionRepository(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM